[LeetCode] 344. 反转字符串
这个算是简单题中的简单题, 双指针一个指向字符串开头, 一个指向字符串结尾, 交换元素后两个指针同时往字符串中心移动 left++ & right--, 直到 left >= right 截止. left == right 的时候不需要交换字符.
class Solution {
public void reverseString(char[] s) {
if (s == null) {
return;
}
for (int left = 0; left < s.length/2; left++) {
char temp = s[left];
s[left] = s[s.length - 1 - left];
s[s.length - 1 - left] = temp;
}
}
}
[LeetCode] 541. 反转字符串 II
这一话在字符串转上套了一层壳, 需要计算当前需要反转的字符串的索引区间. 核心思想是: 从 [startIndex, startIndex + k] 这一段是需要反转的, 如果 startIndex + k > word.length - 1, 说明已经超过最大可反转的字符串了, 因此应该是 [startIndex, word.length - 1], 翻转后需要更新字符串的起始位置 startIndex += 2k.
class Solution {
public String reverseStr(String s, int k) {
if (s == null) {
return s;
}
char[] chars = s.toCharArray();
int charIndex = 0;
while (charIndex < chars.length) {
if (charIndex + k < chars.length) {
reverseStr(chars, charIndex, charIndex + k - 1);
} else {
reverseStr(chars, charIndex, chars.length - 1);
}
charIndex += 2 * k;
}
return new String(chars);
}
private void reverseStr(char[] chars, int start, int end) {
while (start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
}
}
[KamaCoder] 54. 替换数字(第八期模拟笔试)
这一题怎么说呢, 如果用 StringBuilder 很容易就写出来了. 但是题意本身是希望锻炼双指针的思想.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String str = scanner.nextLine();
if (str == null || str.length() == 0) {
break;
}
char[] str2CharsOld = str.toCharArray();
int newCharCount = 0;
for (char strChar : str2CharsOld) {
if (strChar >= '0' && strChar <= '9') {
newCharCount += 6;
} else {
newCharCount += 1;
}
}
char[] str2Chars = new char[newCharCount];
for (int i = 0; i < str2CharsOld.length; i++) {
str2Chars[i] = str2CharsOld[i];
}
int index = str2Chars.length - 1;
for (int i = str2CharsOld.length - 1; i >= 0; i--) {
if (str2CharsOld[i] >= '0' && str2CharsOld[i] <= '9') {
str2Chars[index--] = 'r';
str2Chars[index--] = 'e';
str2Chars[index--] = 'b';
str2Chars[index--] = 'm';
str2Chars[index--] = 'u';
str2Chars[index--] = 'n';
} else {
str2Chars[index--] = str2CharsOld[i];
}
}
System.out.println(new String(str2Chars));
}
}
}