Reverse Words in a String

题目:

Given an input string s, reverse the string word by word.
For example, given s = "the sky is blue", return "blue is sky the"

Example Questions Candidate Might Ask:
Q: What constitutes a word?
A: A sequence of non-space characters constitutes a word.
Q: Does tab or newline character count as space characters?
A: Assume the input does not contain any tabs or newline characters.
Q: Could the input string contain leading or trailing spaces?
A: Yes. However, your reversed string should not contain leading or trailing spaces.
Q: How about multiple spaces between two words?
A: Reduce them to a single space in the reversed string.

解答:

 1 public String reverseWords(String s) {
 2 
 3     StringBuilder reversed = new StringBuilder();
 4     int j = s.length();
 5 
 6     for(int i = s.length()-1; i >= 0; i--) {
 7         if(s.charAt(i) == ' ') {
 8             j = i;
 9         } else if(i == 0 || s.charAt(i-1) == ' ') {
10             if(reversed.length() != 0) {
11                 reversed.append(' ');
12             }
13 
14             reversed.append(s.substring(i, j));
15         }
16     }
17 
18     return reversed.toString();
19 }

如果如何只允许使用O(1)的额外空间呢?

 1 public void reverseWords(char[] s) {
 2     reverse(s, 0, s.length);
 3     for(int i = 0, j = 0; j <= s.length; j++) {
 4         if(j == s.length() || s[j] == ' ') {
 5             reverse(s, i, j);
 6             i = j + 1;
 7         }
 8     }
 9 }
10 
11 public void reverse(char[] s, int begin, int end) {
12     for(int i = 0; i < (end - begin) >> 1; i++) {
13         char tmp = s[begin + i];
14         s[begin + i] = s[end -1 - i];
15         s[end -1 - i] = tmp;
16     }
17 }
原文地址:https://www.cnblogs.com/wylwyl/p/10348414.html