反转字符串(力扣344)
class Solution {
public void reverseString(char[] s) {
int left = 0;
int right = s.length - 1;
while(left < right){
char car = s[left];
s[left] = s[right];
s[right] = car;
left++;
right--;
}
}
}
反转字符串2(力扣541)
这题第一时间没有想出i=i+2*k,用i++做结果超时(也可能是不小心写出了死循环)
class Solution {
public String reverseStr(String s, int k) {
char[] ch = s.toCharArray();
for(int i = 0;i < ch.length;i += 2 * k){
int start = i;
int end = Math.min(ch.length - 1,start + k - 1);
while(start < end){
char temp = ch[start];
ch[start] = ch[end];
ch[end] = temp;
start++;
end--;
}
}
return new String(ch);
}
}
替换空格(剑指offer05)
我的思路:创建另一个字符数组存放,但是“%20”为字符串不能存放在字符数组中;(惨)
class Solution {
public String replaceSpace(String s) {
StringBuffer sb = new StringBuffer();
char[] ar = s.toCharArray();
for(int i = 0; i < s.length(); i++){
if(ar[i] == ' '){
sb.append("%20");
}else{
sb.append(ar[i]);
}
}
return sb.toString();
}
}
反转字符串中单词(力扣151)
我的思路:这题我原本吸取了上一题的教训准备使用StringBuffer,结果内存超出限制,看了解题思路后自己写,在while(i = 0&&ch[i] == ’ ')忘记‘>’,结果死循环了;
class Solution {
public String reverseWords(String s) {
int n = s.length();
char[] newch = new char[n + 1];
char[] ch = s.toCharArray();
int i = n - 1;
int j = 0;
while(i >= 0){
while(i >= 0&& ch[i] == ' ') i--;
int right = i;
while(i >= 0&& ch[i] != ' ') i--;
int left = i + 1;
for(;left <= right; left ++){
newch[j++] = ch[left];
if(left == right){
newch[j++] = ' ';
}
}
}
return new String(newch, 0, j-1);
}
}
左旋转字符(剑指offer58)
我的思路:创建一个新的字符数组存取,没有想出来如何用O(1)的内存空间解决;
题解思路:
class Solution {
public String reverseLeftWords(String s, int n) {
char[] ch = s.toCharArray();
reves(ch, 0, n-1);
reves(ch, n, ch.length-1);
reves(ch, 0, ch.length-1);
return new String(ch);
}
void reves(char[] ch, int left, int right){
while(left < right){
char ar = ch[left];
ch[left] = ch[right];
ch[right] = ar;
left++;
right--;
}
}
}