一、LeetCode 344 反转字符串
题目链接: 344.反转字符串https://leetcode.cn/problems/reverse-string/
思路:双指针法交换。
class Solution {public void reverseString(char[] s) {int n = s.length;int left = 0, right = n-1;while(left < right){char temp = s[left];s[left] = s[right];s[right] = temp;left++;right--;}}
}
二、LeetCode 541 反转字符串II
题目链接:541.反转字符串IIhttps://leetcode.cn/problems/reverse-string-ii/
思路:双指针按块反转。
class Solution {public String reverseStr(String s, int k) {char[] cs = s.toCharArray();int n = cs.length;int left = 0, right = 0;while(n >= 2*k){right = left+k-1;reverse(cs,left,right);n -= 2*k;left = left + 2*k;}if(n >= k){right = left+k-1;reverse(cs,left,right);}else{reverse(cs,left,cs.length-1);}return new String(cs);}public void reverse(char[] cs, int left, int right){while(left < right){char temp = cs[left];cs[left] = cs[right];cs[right] = temp;left++;right--;}}
}
三、卡码网 54 替换数字
题目链接:54.替换数字https://kamacoder.com/problempage.php?pid=1064
思路:使用StringBuilder类的append方法,遍历字符串得到答案。
import java.util.*;
import java.lang.*;
public class Main{public static void main(String args[]){Scanner sc = new Scanner(System.in);String s = sc.nextLine();StringBuilder sb = new StringBuilder();for(int i = 0; i < s.length(); i++){if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){sb.append("number");}else{sb.append(s.charAt(i));}}System.out.print(sb.toString());}
}
四、LeetCode 151 反转字符串中的单词
题目链接:151.反转字符串中的单词https://leetcode.cn/problems/reverse-words-in-a-string/
思路:先去除首尾空格,再把字符串中的单词都存储到ArrayList中,最后倒序输出到Stringbuilder中,得到最终结果。
class Solution {public String reverseWords(String s) {List<String> list = new ArrayList<>();String ss = s.trim();char[] cs = ss.toCharArray();int left = 0;for(int i = 0; i < cs.length; i++){if(cs[i] == ' '){list.add(ss.substring(left,i));while(cs[i] == ' '){i++;}left = i;}}list.add(ss.substring(left,cs.length));StringBuilder sb = new StringBuilder();for(int i = list.size()-1; i >= 0; i--){sb.append(list.get(i));sb.append(" ");}return sb.toString().trim();}
}
五、卡码网 55 右旋转字符串
题目链接: 55.右旋转字符串
思路:先让k进行对n的求余,再截取后k个字符为子串1,剩余字符为子串2,创建StringBuilder把子串1和子串2合成可得出答案。
import java.util.*;
import java.lang.*;
public class Main{public static void main(String args[]){Scanner sc = new Scanner(System.in);int k = sc.nextInt();String s = sc.next();int n = s.length();k = k%n;String s1 = s.substring(n-k,n);String s2 = s.substring(0,n-k);StringBuilder sb = new StringBuilder();sb.append(s1);sb.append(s2);System.out.print(sb.toString());}
}
六、今日小结
重学Java String的各种方法,有一种“温故而知新”的感觉;题目不是很难,回顾了很多字符串处理的方法和思想;明天继续加油*ovo!