344.力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
双指针的思想。左端为left,右端为right,交换left和right上的数值知道left >= right,其中=对应的是奇数个元素的数组,>对应的是偶数个元素的数组。
class Solution {
public void reverseString(char[] s) {
int left = 0;
int right = s.length - 1;
char temp;
while(left < right){
temp = s[left];
s[left] = s[right];
s[right] = temp;
left ++;
right --;
}
}
}
541.力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
这道题不难就是有点麻烦,真的很麻烦。
class Solution {
public String reverseStr(String s, int k) {
StringBuilder result = new StringBuilder();
int i = 0;
int length = s.length() - 1;
while(i <= length){
StringBuilder sb = new StringBuilder();
if(length - i >= k && length - i < 2*k){
sb.append(s.substring(i, i + k));
sb.reverse();
result.append(sb);
result.append(s.substring(i +k));
} else if (length - i < k) {
sb.append(s.substring(i));
sb.reverse();
result.append(sb);
}else{
sb.append(s.substring(i, i + k));
sb.reverse();
result.append(sb);
result.append(s.substring(i + k, i+ 2*k));
}
i = i + 2*k;
}
return result.toString();
}
}
54.替换数字
很简单
public static String reverseStr(String s) {
StringBuilder sb = new StringBuilder();
int i = 0;
int length = s.length()-1;
while(i <= length){
if (s.charAt(i) >= '0' && s.charAt(i) <= '9'){
sb.append("number");
}else{
sb.append(s.charAt(i));
}
i++;
}
return sb.toString();
}
}
151.力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
常规解法分为几步:
1.split指令 以空格为regex划分;
2.对得到的判断是否为“”,如果不是则保留;
3.反转字符串 并加空格
class Solution {
public String reverseWords(String s) {
String[] split1 = s.split(" ");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < split1.length; i++) {
if(split1[i] != ""){
list.add(split1[i]);
}
}
String[] split = list.toArray(new String[list.size()]);
int left = 0;
int right = split.length - 1;
while(left < right){
String temp = split[right];
split[right] = split[left];
split[left] = temp;
left++;
right--;
}
StringBuilder sj = new StringBuilder();
for (int i = 0; i < split.length; i++) {
if(i != split.length - 1){
sj.append(split[i]).append(" ");
}else{
sj.append(split[i]);
}
}
return sj.toString();
}
}
如果用随想录的双指针解法:
55.题目页面
我自己的方法:
1.找到要右旋的起始位置
2.StringBuilder转一下
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.next());
String s = sc.next();
int length = s.length();
int i = length - num;
StringBuilder sb = new StringBuilder();
sb.append(s.substring(i)).append(s, 0, i);
System.out.println(sb.toString());
}
}