leetcode 344 反转字符串
直接首位设置头尾指针 头向右 尾向左 一边遍历 一遍交换
class Solution {
public void reverseString(char[] s) {
int left=0;
int right=s.length-1;
while(left<right){
char temp=s[left];
s[left]=s[right];
s[right]=temp;
left++;
right--;
}
}
leetcode541反转字符串 II
class Solution {
public String reverseStr(String s, int k) {
char[] arr_s=s.toCharArray(); 先将字符串转成字符数组
for(int i=0;i<arr_s.length;i=i+2*k){ //每次跳2k
int left=i,right=Math.min(arr_s.length-1,i+k-1); // 注意边界问题 不一定长度>k
while(left<right){
char tmep=arr_s[right];
arr_s[right]=arr_s[left];
arr_s[left]=tmep;
right--;
left++;
}
}
return new String(arr_s);
}
}
151. 反转字符串中的单词
class Solution {
public String reverseWords(String s) {
// System.out.println("ReverseWords.reverseWords2() called with: s = [" + s + "]");
// 1.去除首尾以及中间多余空格
StringBuilder sb = removeSpace(s);
// 2.反转整个字符串
reverseString(sb, 0, sb.length() - 1);
// 3.反转各个单词
reverseEachWord(sb);
return sb.toString();
}
private StringBuilder removeSpace(String s) { //先移除 边界的空格
int start = 0;
int end = s.length() - 1;
while (s.charAt(start) == ' ') start++;
while (s.charAt(end) == ' ') end--;
StringBuilder sb = new StringBuilder();
while (start <= end) {
char c = s.charAt(start);
if (c != ' ' || sb.charAt(sb.length() - 1) != ' ') { //这一行后面的条件 还不太懂什么意思
sb.append(c);
}
start++;
}
return sb;
}
/**
* 反转字符串指定区间[start, end]的字符
*/
public void reverseString(StringBuilder sb, int start, int end) { //反转指定区间的字符
while (start < end) {
char temp = sb.charAt(start);
sb.setCharAt(start, sb.charAt(end)); //不能直接使用=赋值
sb.setCharAt(end, temp);
start++;
end--;
}
// System.out.println("ReverseWords.reverseString returned: sb = [" + sb + "]");
}
private void reverseEachWord(StringBuilder sb) {
int start = 0;
int end = 1;
int n = sb.length();
while (start < n) {
while (end < n && sb.charAt(end) != ' ') {
end++;
}
reverseString(sb, start, end - 1);
start = end + 1;
end = start + 1;
}
}
}
标签:day08,String,int,StringBuilder,start,while,sb
From: https://www.cnblogs.com/wdnmdp/p/16743396.html