Reverse Words in a String I & Reverse Words in a String II

时间:2023-03-08 20:07:05

Reverse Words in a String I

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

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.
分析:
先取出多余的white space, 然后再进行(A^TB^T)^T = BA的转换。
 public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() < ) return s;
int i = ;
StringBuilder sb = new StringBuilder();
while (i < s.length()) {
StringBuilder temp = new StringBuilder();
while(i < s.length() && !(s.charAt(i) == ' ')) {
temp.insert(, s.charAt(i));
i++;
}
if (temp.length() != ) {
sb.append(temp.toString());
sb.append(' ');
}
while(i < s.length() && s.charAt(i) == ' ') {
i++;
}
}
if (sb.length() > ) {
sb.deleteCharAt(sb.length() - );
}
char[] arr = sb.toString().toCharArray();
reverse(arr); return new String(arr);
} public void reverse(char[] arr) {
int i = , j = arr.length - ;
while (i < j) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
}

 Reverse Words in a String II

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

 public class Solution {
public String reverseWords(String s) {
char[] ca = s.toCharArray();
int start = ;
for (int i = ; i <= ca.length; i++) {
if (i == ca.length || ca[i] == ' ') {
reverse(ca, start, i - );
start = i + ;
}
}
return new String(ca);
} private void reverse(char[] ca, int i, int j) {
for (; i < j; i++, j--) {
char tmp = ca[i];
ca[i] = ca[j];
ca[j] = tmp;
}
}
}