代码随想录算法训练营Day7
344.反转字符串
力扣题目链接:. - 力扣(LeetCode)
双指针
class Solution {
public void reverseString(char[] s) {
int leftindex=0;
int rightindex=s.length-1;
while(leftindex<rightindex){
char temp=s[leftindex];
s[leftindex]=s[rightindex];
s[rightindex]=temp;
leftindex++;
rightindex--;
}
}
}
541. 反转字符串II
力扣题目链接:. - 力扣(LeetCode)
双指针
class Solution {
public String reverseStr(String s, int k) {
char[] sarray=s.toCharArray();
for(int i=0;i<sarray.length;i+=2*k){
int start=i;
int end=Math.min(sarray.length-1,i+k-1);
while(start<end){
char temp=sarray[start];
sarray[start]=sarray[end];
sarray[end]=temp;
start++;
end--;
}
}
return new String(sarray);
}
}
卡码网:54.替换数字
卡码题目链接:54. 替换数字(第八期模拟笔试)
import java.util.Scanner;
public class Main {
public static String replaceNumber(String s) {
int count = 0; // 统计数字的个数
int sOldSize = s.length();
for (int i = 0; i < s.length(); i++) {
if(Character.isDigit(s.charAt(i))){
count++;
}
}
// 扩充字符串s的大小,也就是每个空格替换成"number"之后的大小
char[] newS = new char[s.length() + count * 5];
int sNewSize = newS.length;
// 将旧字符串的内容填入新数组
System.arraycopy(s.toCharArray(), 0, newS, 0, sOldSize);
// 从后先前将空格替换为"number"
for (int i = sNewSize - 1, j = sOldSize - 1; j < i; j--, i--) {
if (!Character.isDigit(newS[j])) {
newS[i] = newS[j];
} else {
newS[i] = 'r';
newS[i - 1] = 'e';
newS[i - 2] = 'b';
newS[i - 3] = 'm';
newS[i - 4] = 'u';
newS[i - 5] = 'n';
i -= 5;
}
}
return new String(newS);
};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
System.out.println(replaceNumber(s));
scanner.close();
}
}