344.反转字符串
🔗题目链接:力扣
💡解题思路:双指针
设置收尾指针,依序交换。
代码如下:
public void reverseString(char[] s) {
int left = 0;
int right = s.length - 1;
char temp;
while(left < right) {
temp = s[left];
s[left++] = s[right];
s[right--] = temp;
}
}
541. 反转字符串II
🔗题目链接:力扣
💡解题思路:每次循环i + 2k,学习continue的用法。
这道题自己做时非常绕,看答案竟如此清晰明了,哭辽
代码如下:
public String reverseStr(String s, int k) {
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i += 2 * k) {
if(i + k <= ch.length) {
reverse(ch, i, i + k - 1);
continue;
}
reverse(ch, i, ch.length - 1);
}
return new String(ch);
}
public void reverse(char[] ss, int left, int right) {
for (; left < right; left++, right--) {
char temp = ss[left];
ss[left] = ss[right];
ss[right] = temp;
}
}
剑指Offer 05.替换空格
🔗题目链接:力扣
💡解题思路:双指针
①扩充数组,先遍历字符串,每遇到空格,则在字符串后添加两个空格
②设置前后指针,从后填充
代码如下:
public String replaceSpace(String s) {
if(s == null || s.length() == 0) {
return s;
}
StringBuilder str = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' ') {
str.append(" ");
}
}
if(str.length() == 0) {
return s;
}
int left = s.length() - 1;
s += str.toString();
int right = s.length() - 1;
char[] chars = s.toCharArray();
while (left > 0) {
if(chars[left] == ' ') {
chars[right--] = '0';
chars[right--] = '2';
chars[right] = '%';
} else {
chars[right] = chars[left];
}
left--;
right--;
}
return new String(chars);
}
151.翻转字符串里的单词
🔗题目链接:力扣
💡解题思路:
- 移除多余空格
- 将整个字符串反转
- 将每个单词反转
代码如下:
//反转字符串中的单词
public String reverseWords(String s) {
StringBuilder sb = deleteSpace(s);
reverseStr(sb, 0, s.length() - 1);
reverseWord(sb);
return sb.toString();
}
//删除多余空格
public StringBuilder deleteSpace(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 reverseStr(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--;
}
}
//反转单词
public void reverseWord(StringBuilder s) {
int start = 0;
int end = 1;
while(start < s.length()) {
while(end < s.length() && s.charAt(end) != ' ') {
end++;
}
reverseStr(s, start, end - 1);
start = end + 1;
end = start + 1;
}
}
剑指Offer58-II.左旋转字符串
🔗题目链接:力扣
💡解题思路:反转就完事
先反转前n个,再反转后n个,最后一起反转
代码如下:
public String reverseLeftWords(String s, int n) {
StringBuilder sb = new StringBuilder(s);
reverseStr(sb, 0, n - 1);
reverseStr(sb, n, sb.length() - 1);
reverseStr(sb, 0, s.length() - 1);
return sb.toString();
}
public void reverseStr(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--;
}
}
📝今日心得
复习了一下StringBuilder的用法,总结学习了字符串里涉及的反转与双指针,有点难度,主要很难独立思考出来,希望下次遇到同类型的题时能有思路。
😈 在沉默中爆发