344.翻转字符串[https://leetcode.cn/problems/reverse-string/submissions/496111203/]
思路:类似于原地翻转数组,左指针右指针向中间靠拢,交换对应元素。
class Solution {
public void reverseString(char[] s) {
int left=0;
int right = s.length-1;
char temp;
while(right > left){
temp=s[left];
s[left] =s[right];
s[right] = temp;
left++;
right--;
}
}
}
**-----------------------分割线-------------------------**
卡码网54.替换数字[https://kamacoder.com/problempage.php?pid=1064]
思路:ez
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
StringBuilder sb = new StringBuilder();
StringBuilder number = new StringBuilder("number");
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) - '0' >= 0 && s.charAt(i) - '9' <= 0) {
sb.append(number);
} else {
sb.append(s.charAt(i));
}
}
System.out.println(sb.toString());
}
}
**-----------------------分割线-------------------------**
卡码网55. 右旋字符串[https://kamacoder.com/problempage.php?pid=1065]
思路:就是将字符串分割成左右字符串,再将左字符串拼接到右字符串后。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
String temp_01 = s.substring(s.length() - k);
String temp_02 = s.substring(0, s.length() - k);
StringBuilder sb = new StringBuilder(temp_01);
sb.append(temp_02);
System.out.println(sb.toString());
}
}
**-----------------------分割线-------------------------**
151.翻转字符串里的单词[https://leetcode.cn/problems/reverse-words-in-a-string/description/]
思路:从右到左遍历字符串,遍历到空格时,从当前位置再往右遍历保存此单词。
class Solution {
public String reverseWords(String s) {
StringBuilder ans = new StringBuilder();
int i = s.length() - 1;
int last;
int j;
for (; i >= 0; i--) {
if (s.charAt(i) != ' ') {
last = i;
while (i >= 0 && s.charAt(i) != ' ') {
i--;
}
j = i + 1;
while (j <= last) {
ans.append(s.charAt(j));
j++;
}
ans.append(' ');
}
}
ans.deleteCharAt(ans.length() - 1);
return ans.toString();
}
}
**-----------------------分割线-------------------------**
541.反转字符串II[https://leetcode.cn/problems/reverse-string-ii/]
思路:难点在于right要在i+k-1和结尾中取小值!
class Solution {
public String reverseStr(String s, int k) {
StringBuilder sb = new StringBuilder(s);
int right;
int left;
char temp;
int loop = s.length() / k;
for (int i = 0; i < s.length(); i += 2 * k) {
left = i;
right = Math.min((i + k - 1), s.length() - 1);
while (right > left) {
temp = sb.charAt(left);
sb.setCharAt(left, sb.charAt(right));
sb.setCharAt(right, temp);
right--;
left++;
}
}
return sb.toString();
}
}
标签:right,String,temp,int,StringBuilder,代码,随想录,第七天,left
From: https://www.cnblogs.com/cssg/p/17969945