题目描述
151. 反转字符串中的单词 - 力扣(Leetcode)
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| public class ReverseWordsInAString151 { public static void main(String[] args){ System.out.println(new Solution().reverseWords(" hello world ")); } }
class Solution { public String reverseWords(String s) { StringBuilder res = removeSpace(s); System.out.println(res); reverse(res,0,res.length() - 1); System.out.println(res); reverseEachWord(res); return new String(res); }
public StringBuilder removeSpace(String oriStr){ StringBuilder res = new StringBuilder(); int left = 0; int right = oriStr.length() - 1; char[] oriChar = oriStr.toCharArray(); while(oriChar[right] == ' ') right--; while(oriChar[left] == ' ') left++;
while (left <= right) { char c = oriChar[left]; if (c != ' ' || res.charAt(res.length() - 1) != ' ') { res.append(c); } left++; } return res; } public void reverse(StringBuilder oriStr, int start, int end){ while(start < end){ char temp = oriStr.charAt(start); oriStr.setCharAt(start++, oriStr.charAt(end)); oriStr.setCharAt(end--,temp); } } public void reverseEachWord(StringBuilder oriStr){ int start = 0; int end = 1; int len = oriStr.length(); while(start < len){ while(end < len && oriStr.charAt(end) != ' ') end++; reverse(oriStr, start, end - 1); start = end + 1; end = start + 1; } } }
|
个人总结
解题关键:
- 只使用
O(1)
的空间复杂度
- 可以用
StringBuilder
- 记得分好步骤:1. 去空格; 2. 全颠覆; 3. 恢复单词;
我对于++
这个运算符的理解又上一层楼咯。
2023/04/01
我觉得这个题目有点东西的,所以第二天又刷了一次。
这次在++
这种自增运算符处理更优雅了,但是我发现我还有两个弱点。
char
老是写成chat
- 对一下Java基础语法不太熟练。比如
setCharAt()
里面是两个参数,index 和 updataValue。