输入一个string,把里面每个单词翻转,例如”this is a test”, 输出”tset a si siht”
并且题目保证了string里只有小写字母和空格,并且有k个单词的话一定只有k – 1个空格
My code:
public String reverse(String s) {
if (s == null || s.length() == 0)
return s;
StringBuilder sb = new StringBuilder();
int begin = s.length() - 1;
int end = s.length() - 1;
while (end >= 0) {
if (begin == end) {
if (s.charAt(begin) == ' ') {
begin--;
end--;
}
else {
sb.append(s.charAt(end));
end--;
}
}
else if (s.charAt(end) != ' ') {
sb.append(s.charAt(end));
end--;
}
else if (s.charAt(end) == ' ') {
sb.append(" ");
end--;
begin = end;
}
}
if (end < begin) {
return sb.toString();
}
else {
return sb.substring(0, sb.length() - 1);
}
}
没什么好说的。reverse string. 然后用 stringbuilder 倒序把他们收集起来。注意空格。
Anyway, Good luck, Richardo!