今日任务
● 344.反转字符串
● 541. 反转字符串II
● 卡码网:54.替换数字
详细布置
344.反转字符串
建议: 本题是字符串基础题目,就是考察 reverse 函数的实现,同时也明确一下 平时刷题什么时候用 库函数,什么时候 不用库函数
题目链接/文章讲解/视频讲解:https://programmercarl.com/0344.%E5%8F%8D%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2.html
class Solution {
public void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while(left < right){
char temp = s [left];
s [left] = s [right];
s[right] = temp;
}
System.out.println('[');
for(char i : s){
System.out.print(i);
System.out.print(',');
}
System.out.println(']');
}
}
超时,什么东西
class Solution {
public void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while(left < right){
char temp = s [left];
s [left] = s [right];
s[right] = temp;
left ++;
right --;
}
}
}
541. 反转字符串II
建议:本题又进阶了,自己先去独立做一做,然后在看题解,对代码技巧会有很深的体会。
class Solution {
public String reverseStr(String s, int k) {
char[] sz = s.toCharArray();
int n = s.length()/(2*k);//1
int m = s.length()%(2*k);//3
for(int i = 0; i < n; i ++){
int left = i*(2*k);
int right = i*(2*k)+k-1;
while(left < right){
char temp = sz [left];
sz [left] = sz [right];
sz[right] = temp;
left ++;
right --;
}
}
if(m < k){
int left = n*(2*k);
int right = s.length() - 1;
while(left < right){
char temp = sz [left];
sz [left] = sz [right];
sz[right] = temp;
left ++;
right --;
}
}else{
int left = (n)*(2*k);
int right = (n)*(2*k)+k-1;
while(left < right){
char temp = sz [left];
sz [left] = sz [right];
sz[right] = temp;
left ++;
right --;
}
}
String str = new String(sz);
return str;
}
}
官方题解: 不用特殊判断
class Solution {
public String reverseStr(String s, int k) {
char[] ch = s.toCharArray();
for(int i = 0;i < ch.length;i += 2 * k){
int start = i;
// 判断尾数够不够k个来取决end指针的位置
int end = Math.min(ch.length - 1,start + k - 1);
while(start < end){
char temp = ch[start];
ch[start] = ch[end];
ch[end] = temp;
start++;
end--;
}
}
return new String(ch);
}
}
题目链接/文章讲解/视频讲解:https://programmercarl.com/0541.%E5%8F%8D%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2II.html
卡码网:54.替换数字
建议:对于线性数据结构,填充或者删除,后序处理会高效的多。好好体会一下。
题目链接/文章讲解:https://programmercarl.com/kama54.%E6%9B%BF%E6%8D%A2%E6%95%B0%E5%AD%97.html
import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
char[] ch = s1.toCharArray();
StringBuilder sb = new StringBuilder();
for(char c : ch){
if (c >= '0' && c <= '9'){
sb.append("number");
}else{
sb.append(c);
}
}
System.out.println(sb.toString());
return;
}
}