輸入一個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!