344、反转字符串
基础,核心逻辑就是i<j
public void reverseString(char[] s) {
for (int i = 0, j = s.length -1; i < j; i++, j--) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
41、反转字符串2 ![](https://i-blog.csdnimg.cn/direct/09ddb94ff1bc4285856cfd70a46f6f1e.png)
for循环不要只会i++,注意i+2k
模拟规则,最后一段长度和k的长度进行比较即可
public String reverseStr(String s, int k) {
//核心在于比较最后一段长度和k
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length - 1; i += 2 * k) {
reverse(ch, i, Math.min(i + k - 1, ch.length - 1));//如果i + k不减1就会多番一个
}
return new String(ch);
}
public void reverse(char[] arr, int left, int right) {
for (int i = left, j = right; i < j; i++, j--) {
char temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
替换数字
思路就是:先扩充数组到该有的范围,再从后往前在新的数组中填入即可 不要从前往后,不然time会变成n2
这也是个双指针问题
import java.util.Scanner;
public class Main {
public static String reverseNumber(String s) {
int count = 0;
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (ch[i] - 'a' < 0) {
count++;
}
}
char[] result = new char[ch.length + count * 5];
int j = result.length - 1;
for (int i = ch.length - 1; i >= 0; i--) {
if (ch[i] - 'a' >= 0) {
result[j] = ch[i];
j--;
}else {
result[j] = 'r';
result[j - 1] = 'e';
result[j - 2] = 'b';
result[j - 3] = 'm';
result[j - 4] = 'u';
result[j - 5] = 'n';
j = j - 6;
}
}
return new String(result);
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println(reverseNumber(s));
sc.close();
}