344.反转字符串
leetcode题目链接:https://leetcode.cn/problems/reverse-string
leetcode AC记录:
代码如下(双指针):
public void reverseString(char[] s) {
//双指针
int left = 0,right = s.length - 1;
while(left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
541. 反转字符串II
leetcode题目链接:https://leetcode.cn/problems/reverse-string-ii
leetcode AC记录:
代码如下:
public String reverseStr(String s, int k) {
int size = s.length();
int index = 0;
String res = s;
while(index < size) {
if(size - index >= 2 * k) {
res = reverseStr(res, index, index + k-1);
index += 2 * k;
} else if(size - index < k) {
res = reverseStr(res, index, size - 1);
index = size;
} else if(size - index < 2 * k && size - index >= k) {
res = reverseStr(res, index, index + k -1);
index = size;
}
}
return res;
}
/**
* 从begin到end 反转s
*/
public String reverseStr(String s, int begin, int end) {
StringBuilder sb = new StringBuilder();
for(int i = 0;i < s.length();i++) {
if(i < begin || i > end) {
sb.append(s.charAt(i));
}
if(begin <= i && i <= end) {
int index = end;
while(index >= begin) {
sb.append(s.charAt(index));
index--;
}
i = end;
}
}
return sb.toString();
}
剑指offer 05.替换空格
leetcode题目链接:https://leetcode.cn/problems/ti-huan-kong-ge-lcof
leetcode AC记录:
代码如下:
public String replaceSpace(String s) {
StringBuilder sb = new StringBuilder();
for(int i = 0;i < s.length();i++) {
if(s.charAt(i) == ' ') {
sb.append("%20");
} else {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
151.翻转字符串里的单词
leetcode题目链接:https://leetcode.cn/problems/reverse-words-in-a-string
leetcode AC记录:
思路:使用栈做反转,使用split函数以空格为分割切单词;
代码如下:
public String reverseWords(String s) {
String[] sArr = s.split(" ");
Stack<String> stack = new Stack<>();
for(int i = 0;i < sArr.length;i++) {
if(!sArr[i].equals("")) {
stack.add(sArr[i]);
}
}
StringBuilder sb = new StringBuilder();
while(!stack.empty()) {
sb.append(stack.pop()).append(" ");
}
return sb.toString().trim();
}
剑指Offer58-II.左旋转字符串
leetcode题目链接:https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof
leetcode AC记录:
代码如下:
public String reverseLeftWords(String s, int n) {
int realN = n % s.length();
System.out.println(realN);
if(realN == 0) {
return s;
}
StringBuilder sb = new StringBuilder();
sb.append(s.substring(realN, s.length()));
sb.append(s.substring(0, realN));
return sb.toString();
}