代码随想录算法训练营
今日任务
344.反转字符串 ,541. 反转字符串II ,卡码网:54.替换数字 ,151.翻转字符串里的单词 ,卡码网:55.右旋转字符串
344.反转字符串
class Solution {
public void reverseString(char[] s) {
int len=s.length;
for (int i = 0; i <= (s.length/2)-1; i++) {
char temp=s[i];
s[i]=s[len-1-i];
s[len-1-i]=temp;
}
}
}
541. 反转字符串II
class Solution {
public String reverseStr(String s, int k) {
if(s.length()==1){
return s;
}
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(i%k==0){
int n=i/k;
if(n%2==0){
int start=i;
int end=i+k-1;
reserve(start,end,ch);
}
}
}
String s1 = new String(ch);
return s1;
}
public void reserve(int start,int end,char[] c){
if(end>=c.length){
end=c.length-1;
}
int len=end-start+1;
int bound=(len/2)+start;
for (int i = start; i < bound; i++) {
char temp=c[i];
c[i]=c[start+end-i];
c[start+end-i]=temp;
}
}
}
卡码网:54.替换数字
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String s = sc.nextLine();
StringBuilder sb=new StringBuilder();
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
char c=ch[i];
if(c>='0'&&c<='9'){
sb.append("number");
}else{
sb.append(c);
}
}
String s1 = sb.toString();
System.out.println(s1);
}
}
151.翻转字符串里的单词
//之前还以为要反转每一个单词hhh
class Solution {
public String reverseWords(String s) {
StringBuilder sb=new StringBuilder();
String[] split = s.split(" ");
int count=0;
for (String s1 : split) {
if(s1!=""){
count++;
}
}
for (int i = split.length-1; i >= 0; i--) {
if(split[i]!=""){
sb.append(split[i]);
count--;
if(count!=0){
sb.append(" ");
}
}
}
String s1 = sb.toString();
return s1;
}
}
卡码网:55.右旋转字符串
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int k = Integer.parseInt(sc.nextLine());
String s = sc.nextLine();
char[] ch = s.toCharArray();
int len=s.length();
int start=len-k;
int end=len-1;
StringBuilder sb=new StringBuilder();
for (int i = start; i <= end; i++) {
sb.append(ch[i]);
}
if(start-1>=0){
for (int i = 0; i < start; i++) {
sb.append(ch[i]);
}
}
String s1 = sb.toString();
System.out.println(s1);
}
}
最近吊水(身心疲惫)所以做题很拖沓