代码随想录 (programmercarl.com)
344.反转字符串
循环条件:i和j可等可不等
class Solution {
public void reverseString(char[] s) {
int i = 0;
int j = s.length - 1;
while (i < j){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
return;
}
}
541. 反转字符串II
题目的意思概括为:每隔2k个反转前k个,尾数不够k个全部反转
直接操作前2k个,i += 2 * k
class Solution {
public String reverseStr(String s, int k) {
String result = new String();
char[] c = s.toCharArray();
for(int i = 0; i < s.length() - 1; i += 2 * k){
int start = i;
int end = Math.min(s.length() - 1, start + k - 1);
while (start < end){
char temp = c[start];
c[start] = c[end];
c[end] = temp;
start++;
end--;
}
}
result = String.valueOf(c);
return result;
}
}
剑指Offer 05.替换空格-LCR 122.路径加密
class Solution {
public String pathEncryption(String path) {
String result = new String();
char[] s = path.toCharArray();
for (int i = 0; i < path.length(); i++){
if(s[i] == '.'){
s[i] = ' ';
}
}
result = String.valueOf(s);
return result;
}
}
151.翻转字符串里的单词
class Solution {
public String reverseWords(String s) {
// 除去开头和末尾的空白字符
s = s.trim();
// 正则匹配连续的空白字符作为分隔符分割
List<String> wordList = Arrays.asList(s.split("\\s+"));
Collections.reverse(wordList);
return String.join(" ", wordList);
}
}
剑指Offer58-II.左旋转字符串-LCR 182.动态口令
class Solution {
public String dynamicPassword(String password, int target) {
char[] chars = password.toCharArray();
reverse(chars, 0, target - 1);
reverse(chars, target, chars.length - 1);
reverse(chars, 0, chars.length - 1);
// return String.valueOf(chars);
return new String(chars);
}
public void reverse(char[] chars, int left, int right){
while (left < right){
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
}
}