剑指 Offer 05. 替换空格
https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
主要考察字符串的操作,字符串转成字符数组,字符数组变成字符串。也可以采用StringBuffer实现。
- 代码如下:
class Solution {
public String replaceSpace(String s) {
int l = s.length();
char[] array=new char[l*3];
int size =0;
for(int i=0;i<l;i++){
char c = s.charAt(i);
if(c==' '){
array[size++] = '%';
array[size++] = '2';
array[size++] = '0';
}else{
array[size++] = c;
}
}
String newS = new String(array,0,size);
return newS;
}
}
剑指 Offer 58 - II. 左旋转字符串
https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
考察字符串操作。
- 代码1:切片
return s.substring(n,s.length())+s.substring(0,n);
- 代码2:StringBuffer()拼接
class Solution {
public String reverseLeftWords(String s, int n) {
StringBuffer res = new StringBuffer();
for(int i=n;i<s.length();i++){
res.append(s.charAt(i));
}
for(int i=0;i<n;i++){
res.append(s.charAt(i));
}
return res.toString();
}
}
- 代码3:求余代替两次循环
class Solution {
public String reverseLeftWords(String s, int n) {
String res = "";
for(int i=n;i<s.length()+n;i++){
res +=s.charAt(i%s.length());
}
return res;
}
}