Closed labuladong closed 1 year ago
Q48. Rotate Image https://leetcode.com/problems/rotate-image/discuss/3864950/Java-Solution
[59. Spiral Matrix II] https://leetcode.com/problems/spiral-matrix-ii/solutions/3864985/4-boundaries/
[48]旋转图像 https://leetcode.cn/problems/rotate-image/solutions/2373748/48-xuan-zhuan-tu-xiang-by-wangyin717-ji75/ [54]螺旋矩阵 https://leetcode.cn/problems/spiral-matrix/solutions/2373794/54-luo-xuan-ju-zhen-by-wangyin717-h0xg/ [59]螺旋矩阵 II https://leetcode.cn/problems/spiral-matrix-ii/solutions/2373816/59-luo-xuan-ju-zhen-ii-by-wangyin717-ojv3/
48.https://leetcode.cn/problems/rotate-image/solutions/2374102/xuan-zhuan-tu-xiang-by-betodea-xg5p/ 54.https://leetcode.cn/problems/spiral-matrix/solutions/2374125/luo-xuan-ju-zhen-by-betodea-deks/ 59.https://leetcode.cn/problems/spiral-matrix-ii/solutions/2374172/luo-xuan-ju-zhen-ii-by-betodea-sstt/
https://leetcode.cn/problems/reverse-words-in-a-string/solutions/2374494/cong-hou-wang-qian-bian-li-li-yong-strin-iu6j/ 参考 https://leetcode.cn/problems/reverse-words-in-a-string/solutions/194450/fan-zhuan-zi-fu-chuan-li-de-dan-ci-by-leetcode-sol/comments/1547002
从后往前遍历,利用 string 的 append 方法,在遍历中把单词依次拼接在一起。
class Solution {
public String reverseWords(String s) {
// 每个单词的开始和结束索引(左闭右开)
int start;
int end;
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; i--) {
// 跳过空格。这里不能用 while {i--},因为 for 循环里还有一个
// i--,下次 for 循环执行到这里会减两次 i。
if (s.charAt(i) == ' ') {
continue;
}
// 找到结束索引,此时 charAt(i) 不是空格,charAt(i+1) 是
end = i + 1;
// 跳过空格,这里不能用
// if continue
// 因为 continue 后会先执行上面的代码,我们希望遇到非空字符
// 直接左移,不要做前面的操作
while (i >= 0 && s.charAt(i) != ' ') {
i--;
}
// 找到开始索引,此时 charAt(i) 是空格,charAt(i+1) 不是
start = i + 1;
// 将每个单词按开始结束索引赋值到 StringBuilder,用
// sb.append(s.substring(start, end));
// 也可以,但是会占用更多内存
for (int j = start; j < end; j++) {
sb.append(s.charAt(j));
}
// 每个单词之间都要有一个空格
sb.append(' ');
}
// 删掉最后一个多余的空格
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
本期打卡已结算完成。报名最新一期的打卡活动 点这里