提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
class Solution {
public void reverseString(char[] s) {
for(int i = 0, j = s.length-1; i < j; i++, j --){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
class Solution {
public String reverseStr(String s, int k) {
char[] ch = s.toCharArray();
int low, high;
for(low = 0, high = k-1; high < ch.length;low += 2*k, high += 2*k){
reverseFun(ch, low,high);
}
if(low < ch.length){
reverseFun(ch, low, ch.length-1);
}
return new String(ch);
}
public void reverseFun(char[] ch, int low, int high){
for(int i = low, j = high; i < j; i ++, j --){
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
}
}
}
class Solution {
public String replaceSpace(String s) {
// List list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for(int i = 0;i < s.length(); i ++){
if(s.charAt(i) == ' '){
sb.append('%');
sb.append('2');
sb.append('0');
}else{
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}
双指针法
class Solution {
public String replaceSpace(String s) {
int count = 0;
for(int i = 0; i < s.length(); i ++){
if(s.charAt(i) == ' '){
count++;
}
}
if(count == 0){
return s;
}
int len = s.length() + 2*count;
char[] res = new char[len];
for(int i = s.length()-1, j = len-1; i >= 0;){
if(s.charAt(i) == ' '){
i--;
res[j--] = '0';
res[j--] = '2';
res[j--] = '%';
}else{
res[j--] = s.charAt(i--);
}
}
return new String(res);
}
}
class Solution {
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
int low, high = 0,i , j;
for(j = 0; j < s.length();){
while(j < s.length() && s.charAt(j) == ' ')j++;
if(j == s.length()){
break;
}
i = j;
while(j < s.length() && s.charAt(j) != ' ')j++;
low = i; high = j-1;
while(high >= low){
sb.append(s.charAt(high--));
}
sb.append(' ');
}
sb.deleteCharAt(sb.length()-1);
sb.reverse();
return sb.toString();
}
}
class Solution {
public String reverseLeftWords(String s, int n) {
char[] ch = s.toCharArray();
fun(ch, 0, n-1);
fun(ch, n, s.length()-1);
fun(ch, 0, s.length()-1);
return String.valueOf(ch);
}
public void fun(char[] ch, int low, int high){
for(int i = low, j = high; i < j; i ++, j --){
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
}
}
}