标签:
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 (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
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 }
标签:
原文地址:http://www.cnblogs.com/qq1029579233/p/4485731.html