344、反转字符串
基本思想:
双指针中的左右指针
具体实现:
代码:
class Solution { public void reverseString(char[] s) { for (int i = 0, j = s.length - 1; i < j; i++, j--){ char temp = s[i]; s[i] = s[j]; s[j] = temp; } } }
541、反转字符串II
class Solution { public String reverseStr(String s, int k) { char[] ch = s.toCharArray(); // 1. 每隔 2k 个字符的前 k 个字符进行反转 for (int i = 0; i< ch.length; i += 2 * k) { // 2. 剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符 if (i + k <= ch.length) { reverse(ch, i, i + k -1); continue; } // 3. 剩余字符少于 k 个,则将剩余字符全部反转 reverse(ch, i, ch.length - 1); } return new String(ch); } // 定义翻转函数 public void reverse(char[] ch, int i, int j) { for (; i < j; i++, j--) { char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; } } }
151、翻转字符串里的单词
具体实现:
1.移除多余空格
2.将整个字符串翻转
3.将每个单词翻转
举例:
- 移除多余空格 : "the sky is blue"
- 字符串反转:"eulb si yks eht"
- 单词反转:"blue is sky the"
class Solution { public String reverseWords(String s) { StringBuilder sb = removeSpace(s); reverseString(sb, 0, sb.length() - 1); reverseEachWorld(sb); return sb.toString(); } private StringBuilder removeSpace(String s){ int start = 0; int end = s.length() - 1; while (s.charAt(start) == ' ') start++; while (s.charAt(end) == ' ') end--; StringBuilder sb = new StringBuilder(); while (start <= end){ char c = s.charAt(start); if (c != ' ' || sb.charAt(sb.length() - 1) != ' '){//防止单词中间的空格有两个 sb.append(c); } start++; } return sb; } public void reverseString(StringBuilder sb, int start, int end){ while(start < end){ char temp = sb.charAt(start); sb.setCharAt(start, sb.charAt(end)); sb.setCharAt(end, temp); start++; end--; } } private void reverseEachWorld(StringBuilder sb){ int start = 0; int end = 1; int n = sb.length(); while (start < n){ while (end < n && sb.charAt(end) != ' '){ end++; } reverseString(sb, start, end - 1); start = end + 1; end = start + 1; } } }
剑指offer58-II左旋转字符串
具体实现:
代码:
class Solution { public String reverseLeftWords(String s, int n) { int len = s.length(); StringBuilder sb = new StringBuilder(s); reverseString(sb, 0, n - 1); reverseString(sb, n, len - 1); return sb.reverse().toString(); } public void reverseString(StringBuilder sb, int start, int end){ while(start < end){ char temp = sb.charAt(start); sb.setCharAt(start, sb.charAt(end)); sb.setCharAt(end, temp); start++; end--; } } }