Leetcode some questions about strings, which are described below:
Given an input string, reverse the string word by word.
For example,
Given s = " the sky is blue
",
Return " blue is sky the
".
Update (2015-02-12):
For C programmers:try to solve it InO (1) space.
Click to show Clarification.
Subscribe to see which companies asked this question
The solution is as follows:
ImportJava.util.*;ImportJava.io.*;Importjava.lang.*; Public classReversewords { Publicstring Reversewords (string s) {StringBuilder reversed=NewStringBuilder (); Building an empty string builderintj =s.length (); for(inti = S.length ()-1; I >= 0; i--) { if(S.charat (i) = = ") {J=i;
}
Else if(i = = 0 | | S.charat (i-1) = = ") { if(Reversed.length ()! = 0{//When the input has only one character, such as "a", this time the program will run to this step, but note that at this point the builder is not content, so Reversed.length () is 0, does not meet the conditions REVERSED.A Ppend (‘ ‘); The space is also to be lost, but at the same time to avoid the two ends is a space, then is not input. } reversed.append (S.substring (i, j)); Note here that the string substring is used, which is consistent with my previous idea that the concatenated strings are intercepted with substring. Here, intercept it and put it into the string Builder}//substring (int i,int j) returns a new string containing the original string Position from the I~j-1 section, note that the subscript does not include J}returnreversed.tostring (); Note that this is the correct output format for the string builder, which returns a string with the same content as the builder (or buffer)}/*private String Rewords (string s) {string b= ""; for (int i=0;i<s.length (); i++) {//for (int j=i;s.charat (j)! = ""; j + +); int j=i; while (Character.isletter (S.charat (j)) && (J<s.length ())) J + +; String a=s.substring (I,J); B=a+b; I=j; } return B; } */ Public Static voidMain (string[] args) {reversewords Reverse=Newreversewords (); String Out_target=reverse.reversewords ("AB CAC cc"); System.out.printf ("The output is" +out_target); System.out.println (); }}
Summary: The commented out part, is my own idea, but does not work, mainly reflected in: I use string connection to solve this problem, so each connection string will produce a knot of string object, time-consuming and wasted space. And the idea is a little confusing.
Cleancode adopted the StringBuilder class so that the question of appeal could be avoided. You can read the relevant content in the StringBuilder class carefully, and you can find it is suitable for solving this problem.
Leetcode Detailed (Reversewords)