344.反转字符串
非常简单,双指针,耗时3:53
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
耗时25:57
优化:
本人思路:
class Solution {
public String reverseStr(String s, int k) {
char[] c = s.toCharArray();
int n1 = c.length / (2 * k);//记录有几个2k
int n2=c.length % (2 * k);
if(n2>0) n1++;//如果还有,则需要继续反转
for (int i = 0; i < n1; i++) {
int left = i * 2 * k, right = left + k - 1;
if(right>=c.length) right=c.length-1;//n2小于k的情况
while (left < right) {
char temp = c[left];
c[left] = c[right];
c[right] = temp;
left++;
right--;
}
}
return new String(c);
}
}
卡码网:54.替换数字
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
char[] c=s.toCharArray();
StringBuffer res=new StringBuffer();
for(int i=0;i<s.length();i++){
if(c[i]<'a' || c[i]>'z'){
res.append("number");
}else{
res.append(c[i]);
}
}
System.out.println(res.toString());
sc.close();
}
}