今日任务
344.反转字符串
541. 反转字符串II
344.反转字符串
题目连接:. - 力扣(LeetCode)
本题知识点: 使用异或的方法实现swap功能。
class Solution {
public void reverseString(char[] s) {
int left = 0;
int right = s.length - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
541. 反转字符串II
题目链接:. - 力扣(LeetCode)
本题知识点
1. String是不可变量,反转时需要将String转换成CharArray进行处理
2. 异或^方式实现swap功能
3. Array转换成字符串方法:
(1) new String(charArray)
(2)String.valueOf(charArray)
class Solution {
public String reverseStr(String s, int k) {
char[] charArray = s.toCharArray();
int i = 0;
for (i = 2 * k; i < s.length(); i += 2 * k) {
swap1(charArray, i - 2 * k, i - k);
}
if (i - s.length() >= k) {
swap1(charArray, i - 2 * k, s.length());
} else {
swap1(charArray, i - 2 * k, i - k);
}
//return new S tring(charArray);
return String.valueOf(charArray);
}
public void swap(char[] charArray, int start , int end) {
int left = start;
int right = end - 1;
while (left < right) {
char character = charArray[left];
charArray[left] = charArray[right];
charArray[right] = character;
left++;
right--;
}
return;
}
public void swap1(char[] charArray, int start , int end) {
int left = start;
int right = end - 1;
while (left < right) {
charArray[left] ^= charArray[right];
charArray[right] ^= charArray[left];
charArray[left] ^= charArray[right];
left++;
right--;
}
return;
}
}