Https://leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.
For example,
Given S ="the sky is blue
",
Return"blue is sky the
".
Update ):
For C programmers: try to solve itIn-PlaceInO(1) space.
Click to show clarification.
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word.
- Cocould the input string contain leading or trailing spaces?
Yes. However, your reversed string shocould not contain leading or trailing spaces.
- How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
1 import java.util.ArrayList; 2 import java.util.List; 3 import java.util.Stack; 4 5 public class Solution { 6 public static String reverseWords(String s) { 7 List<String> li=new ArrayList(); 8 int len0=s.length(); 9 int len1=0;10 String x="";11 for(int i=0;i<len0;i++){12 char c=s.charAt(i);13 if(c!=‘ ‘) x+=c;14 else{15 if(x.length()!=0){16 len1++;17 li.add(x);18 }19 x="";20 }21 }22 if(x.length()!=0) li.add(x);23 Stack<String>st=new Stack();24 for(String str:li){25 st.add(str);26 }27 s="";28 while(!st.isEmpty()){29 s+=st.pop();30 if(st.size()!=0)31 s+=" ";32 }33 return s;34 }35 public static void main(String[]args){36 System.out.println(reverseWords(" a b "));37 }38 }
Reverse words in a string