剑指offer之替换空格
2017-03-07 22:35
537 查看
思路1:将字符串先转化为字符数组,声明一个StringBuffer变量,如果字符为非空格,则追加该字符,否则追加%20
public String replaceSpace(StringBuffer str) {
if (str == null)
return null;
char[] array = str.toString().toCharArray();
StringBuffer s = new StringBuffer();
for (int i = 0; i < array.length; i++) {
if (array[i] == ' ') {
s.append("%20");
continue;
}
s.append(array[i]);
}
return s.toString();
}
思路2:从后往前替换
public String replaceSpace(StringBuffer str) {
if (str == null)
return null;
int spaceNum = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
spaceNum++;
continue;
}
}
int oldLength = str.length();
int newLength = oldLength + spaceNum * 2;
str.setLength(newLength);
for (int oldIndex = oldLength - 1, newIndex = newLength - 1; oldIndex >= 0
&& oldIndex < newIndex; --oldIndex) {
if (str.charAt(oldIndex) == ' ') {
str.setCharAt(newIndex--, '0');
str.setCharAt(newIndex--, '2');
str.setCharAt(newIndex--, '%');
} else {
str.setCharAt(newIndex--, str.charAt(oldIndex));
}
}
return str.toString();
}
public String replaceSpace(StringBuffer str) {
if (str == null)
return null;
char[] array = str.toString().toCharArray();
StringBuffer s = new StringBuffer();
for (int i = 0; i < array.length; i++) {
if (array[i] == ' ') {
s.append("%20");
continue;
}
s.append(array[i]);
}
return s.toString();
}
思路2:从后往前替换
public String replaceSpace(StringBuffer str) {
if (str == null)
return null;
int spaceNum = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
spaceNum++;
continue;
}
}
int oldLength = str.length();
int newLength = oldLength + spaceNum * 2;
str.setLength(newLength);
for (int oldIndex = oldLength - 1, newIndex = newLength - 1; oldIndex >= 0
&& oldIndex < newIndex; --oldIndex) {
if (str.charAt(oldIndex) == ' ') {
str.setCharAt(newIndex--, '0');
str.setCharAt(newIndex--, '2');
str.setCharAt(newIndex--, '%');
} else {
str.setCharAt(newIndex--, str.charAt(oldIndex));
}
}
return str.toString();
}
相关文章推荐
- [剑指OFFER] 替换空格
- 剑指offer替换空格
- 剑指offer-算法题练习:part2 替换空格
- 剑指offer——题目描述 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 【剑指offer】面试题4:替换空格 java
- 剑指Offer--004-替换空格
- 剑指offer面试题java实现之题4:替换空格
- 剑指offer面试题4:替换空格和合并两个有序数组
- 剑指offer刷题之c++实现的替换空格
- 剑指offer-替换空格
- 剑指offer题解【替换空格】-java
- 剑指Offer——替换空格
- 剑指offer—替换空格
- 剑指offer 4---替换空格
- 牛客网-剑指Offer-替换空格
- 【剑指offer】面试题5:替换空格
- 剑指offer面试题4—替换空格
- 【剑指offer——JAVA实现】替换空格
- 剑指offer 面试题4—替换字符串中空格
- 剑指offer面试题4:替换空格