class Solution {
public void reverseString(char[] s) {
int left=0;
int right = s.length-1;
// for(int i=0;i<s.length;i++){
while(left<right){
char temp=s[left];
s[left]=s[right];
s[right]=temp;
left++;
right--;
}
// return s;
}
}
反转k个字符串,取到合适的位置。
关键在于如何去判断剩余字符是少于k 还是小于2k大于k个。
注意:
class Solution {
public String reverseStr(String s, int k) {
char[] c = s.toCharArray();//转为字符数组
// int left=0;
// int right=
for(int i=0;i<c.length;i+=2*k){
int start=i;
int end=Math.min(c.length-1,start+k-1);
while(start<end){
char temp=c[start];
c[start]=c[end];
c[end]=temp;
start++;
end--;
}
}
return new String(c);
}
}
注意:用StringBuilder储存
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
// for(char c:s){
// System.out.println(c);
// }
StringBuilder sb=new StringBuilder();
for(int i=0;i<s.length();i++){
if(Character.isDigit(s.charAt(i))){
sb.append("number");
}else{
sb.append(s.charAt(i));
}
}
System.out.println(sb);
}
}
class Solution {
public String reverseWords(String s) {
String[] s1=s.split(" ");
StringBuilder stringBuilder = new StringBuilder();
for(int i=s1.length-1;i>=0;i--){
// System.out.println(s1[i]);
if(!s1[i].equals("")){
stringBuilder.append(" " + s1[i]);
}
}
return stringBuilder.toString().trim();// 去除空白
}
}
class Solution {
public String reverseWords(String s) {
s=s.trim();
int j=s.length()-1,i=j;
StringBuilder sb = new StringBuilder();
while(i>=0){
while(i>=0&&s.charAt(i)!=' ')i--;//搜索空格
sb.append(s.substring(i+1,j+1)+" ");//添加单词,substring前闭后开,在while循环结束后 i移动到空格了,所以i++
while(i>=0&&s.charAt(i)==' ')i--;//搜索空格
j=i;
}
return sb.toString().trim();
}
}
import java.util.*;
class Main{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int k = s.nextInt();
// 清除输入缓冲区中的换行符
s.nextLine();
//读取字符串
String str = s.nextLine();
StringBuilder sb = new StringBuilder();
// int j=s.length()-1,i=j;
sb.append(str.substring(str.length()-k));
sb.append(str.substring(0,str.length()-k));
System.out.println(sb);
}
}