LeetCode 151题

class Solution {
public String reverseWords(String str) {
if(str.length() == 0) {
return "";
}
StringBuilder resStr = new StringBuilder();
int length = str.length();
for(int i = 0; i < length; i++) {
char c = str.charAt(length - i - 1);
if(c == ' ') {
continue;
}else {
for(int j = i; j < length; j++) {
if(str.charAt(length - j - 1) == ' ') {
resStr.append(str.substring(length - j, length - i));
resStr.append(" ");
i += j-i-1;
break;
}
if(j == length-1) {
resStr.append(str.substring(length - j - 1, length - i));
i += j;
}
}
}
}
if(resStr.toString().charAt(resStr.length() - 1) == ' ') {
resStr.deleteCharAt(resStr.length()-1);
}
return resStr.toString();
}
}

LeetCode 151题解析
本文详细解析了LeetCode 151题“翻转字符串里的单词”的解决方案,通过Java实现,逐字符扫描并反转字符串中的单词,提供了一种有效的方法来处理空格分隔的字符串。
1213

被折叠的 条评论
为什么被折叠?



