344.反转字符串
https://leetcode.cn/problems/reverse-string/description/
比较简单的一题,左右指针循环交换数据
class Solution {
public void reverseString(char[] s) {
if (s == null && s.length <=1) return;
char temp;
int left = 0;
int right = s.length - 1;
while (left < right) {
temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
541. 反转字符串II
https://leetcode.cn/problems/reverse-string-ii/
1.模拟题,题目思路也很简单,这个简单本身是因为数组索引效率比较方便
2.题目和第一题相比多一步,就是每次移动2k,然后反转前k个元素,反转的操作函数可以抽出来
class Solution {
public String reverseStr(String s, int k) {
if (s == null || k <= 0) {
return s;
}
char[] strArray = s.toCharArray();
int pos = 0;
while(pos < strArray.length - 1) {
// 这里需要注意判断条件,剩下的数如果是不足k的话会溢出,一开始写反了
if (pos + k > strArray.length - 1) {
// 剩余字符串少于k个的情况
swap(strArray, pos, strArray.length - 1);
} else {
// 剩余字符串>=k的情况
swap(strArray, pos, pos + k - 1);
}
pos += 2 * k;
}
return new String(strArray);
}
private void swap(char[] s, int begin, int end) {
if (s == null || s.length == 0 || begin < 0 || end < 0) {
return;
}
int left = begin;
int right = end;
while(left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
卡码网替换数字
https://kamacoder.com/problempage.php?pid=1064
该题其实主要是c++里的用法,java由于本身String类型本身不能扩充长度,需要额外开辟空间,而java里的解法就是循环遍历判断、拼接,比较简单,不贴代码了
151.翻转字符串里的单词
https://leetcode.cn/problems/reverse-words-in-a-string/description/
这道题值得多看几遍(明天再来补答案)
右旋字符串
https://kamacoder.com/problempage.php?pid=1065
1.其实这道题的难点原本是不开辟新的空间如何进行右旋,但java的String做不到,必须新建另外一个数据结构进行操作
2.对java的main入口函数如何取数需要单独记忆下
① public static void main(String[] args) 是 Java 程序的入口点。当你执行一个 Java 程序时,JVM (Java 虚拟机) 会自动调用这个方法来启动程序的执行;
② static表示该方法是静态的,属于类而不是实例。静态方法可以直接通过类名调用,无需创建对象实例;
③ Scanner 是 Java 标准库中的一个类,用于读取用户输入。通过创建一个 Scanner 对象,并将其构造函数中的参数设置为 System.in,即表示从标准输入(也就是控制台)读取用户输入。
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
String s = in.nextLine();
int len = s.length(); //获取字符串长度
char[] result = s.toCharArray();
swap(result, 0, len - 1);
swap(result, 0, n - 1);
swap(result, n, len - 1);
System.out.println(result);
}
public static void swap(char[] s, int begin, int end) {
if (begin >= end || s == null || s.length == 0) {
return;
}
int left = begin;
int right = end;
while(left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}