Given an input string, reverse the string word by word.
For example,
Given s = " the sky is blue ",
Return " blue is sky the ".
Solution1: Do not use any functiion
Yesterday Expedia interviewed himself to understand the test instructions wrong, not after the depressed unceasingly. Today re-done again, found that if the restrictions of various function, many corner case to consider, change to spend a long time. So yesterday did not have their own strength caused by nothing to complain about.
Idea: Read with stack, hit the number of space output stack, use StringBuilder to connect the letters together. But there are a lot of cornercase, such as "a", so use prev= ' to record whether you have encountered a space before. If you read a new letter again, change the prev to any other number to distinguish it from the space. After the end of the loop, empty the stack and then decide if "a" will appear, and then empty the last space. Feel like doing a lot of trouble.
Public classSolution { Publicstring Reversewords (string s) {Stack<Character> res=NewStack<character>(); StringBuilder SB=NewStringBuilder (); CharPrev= "; for(intI=s.length () -1;i>=0;i--) { if(S.charat (i)! = ") {Res.push (S.charat (i)); } Else { while(!Res.isempty ()) {Sb.append (Res.pop ()); Prev=0; } if(prev!= ' &&i!=0) {sb.append (" "); } prev= ' '; } } while(!Res.isempty ()) {Sb.append (Res.pop ()); } if(Sb.length () >0&&sb.charat (Sb.length ()-1) = = ") {Sb.deletecharat (Sb.length ()-1); } returnsb.tostring (); }}
Solution2:
Other use function after doing it, it will be much easier. This essay is not expected to meet again.
151. Reverse Words in a String