Reverse String类型
11-23 5:40pm - 6:13pm Bobst
Reverse String
return string reversed
public String reverse(String s) {
if(s == null || s.length() == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for(int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
Reverse Words in a String
思路就是先翻转每个word,然后在翻转整个string
比较麻烦的是处理中间多余的空格
public class Solution {
public String reverseWords(String s) {
if(s == null || s.length() == 0) {
return "";
}
int start = 0;
int i = 0;
int len = s.length();
char[] array = s.toCharArray();
// reverse each word
while(i < len) {
while(i < len && s.charAt(i) == ' ') i++;
start = i;
while(i < len && s.charAt(i) != ' ') i++;
reverse(array, start, i - 1);
}
// reverse the string
StringBuilder sb = new StringBuilder();
i = len - 1;
while(i >= 0) {
// skip the spaces
while(i >= 0 && s.charAt(i) == ' ') i--;
while(i >= 0 && s.charAt(i) != ' ') {
sb.append(array[i--]);
}
sb.append(' ');
}
// remove the trailing space
return sb.toString().trim();
}
private void reverse(char[] array, int start, int end) {
for(int i = start, j = end; i < j; i++, j--) {
char c = array[j];
array[j] = array[i];
array[i] = c;
}
}
}
Reverse Words in a String II
这一题其实是一的简化版,没有多余的空格,直接翻转就可以
public class Solution {
public void reverseWords(char[] s) {
if(s == null || s.length == 0) {
return;
}
int start = 0;
int i = 0;
int len = s.length;
// 怎么样用space来分割每个单词
while(i < len) {
while(i < len && s[i] != ' ') i++;
reverse(s, start, i - 1);
i++;
start = i;
}
reverse(s, 0, len - 1);
}
public void reverse(char[] s, int start, int end) {
while(start < end) {
char temp = s[start];
s[start] = s[end];
s[end] = temp;
start++;
end--;
}
}
}