Q2:Reverse Words in a String
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
MyAnswer 1 (Java):
1 public class Solution { 2 public String reverseWords(String s) { 3 String result = ""; 4 int i = 0; 5 int j = s.length(); 6 for(i = s.length()-1; i >= 0; i--) 7 { 8 if(s.charAt(i) == ' ') 9 { 10 if(i == s.length()-1) 11 { 12 j = i; 13 //continue; 14 } 15 else if(i == 0) 16 { 17 //i++; 18 break; 19 } 20 else if(j == i+1) 21 { 22 j = i; 23 //continue; 24 } 25 else 26 { 27 result = result.concat(s.substring(i+1,j)+" "); 28 j = i; 29 } 30 } 31 } 32 result = result.concat(s.substring(i+1,j)); 33 if(!result.isEmpty() && result.charAt(result.length()-1) == ' ') 34 result = result.substring(0,result.length()-1); 35 return result; 36 } 37 }
使代码更加精简,改为:
MyAnswer 2(Java):
1 public class Solution { 2 public String reverseWords(String s) { 3 4 String result = ""; 5 int j = s.length(); 6 int i = j-1; 7 8 for(; i >= 0; i--) 9 { 10 if(s.charAt(i) == ' ') 11 { 12 if(i == 0) 13 { 14 break; 15 } 16 else if(i != s.length()-1 && j != i+1) 17 { 18 result = result.concat(s.substring(i+1,j)+" "); 19 } 20 j = i; 21 } 22 } 23 24 result = result.concat(s.substring(i+1,j)); 25 26 int k = result.length(); 27 if(!result.isEmpty() && result.charAt(k-1) == ' ') 28 result = result.substring(0,k-1); 29 return result; 30 } 31 }
MyAnswer3 (C++):
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 string result = ""; 5 int j = 0; 6 int i; 7 for(i = s.length()-1; i >= 0; i--) 8 { 9 if(s[i] == ' ') 10 { 11 if(j == 0) 12 continue; 13 result = result + s.substr(i+1, j) + " "; 14 j = 0; 15 continue; 16 } 17 j++; 18 } 19 result = result + s.substr(i+1, j); 20 s = (result[result.length()-1] == ' ')?result.substr(0,result.length()-1):result; 21 } 22 };