/**
* 题目:请实现一个函数,将一个字符串中的每个空格替换成“%20”。
* 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*
* 思路:O(n),先从头到尾扫描所有空格个数m,
* 新字符串的长度为n+2m
* 从字符串末尾开始移动字符
*/
public class E4 {
public static void main(String[] args) {
char a[] = new char[1000];
Scanner scanner = new Scanner(System.in);
System.out.print("input a string: ");
while (scanner.hasNext()) {
String s = scanner.nextLine();
for (int i=0; i<s.length();i++) {
a[i] = s.charAt(i);
}
replaceBlankChar(a);
System.out.println("result: "+String.valueOf(a));
System.out.print("input a string: ");
}
}
private static void replaceBlankChar(char[] a) {
if (a == null || a.length == 0) {
return;
}
int originalLength = 0;
int blankLength = 0;
for (int i=0;i<a.length;i++) {
if (a[i] == '\0') {
break;
}
if (a[i] == ' '){
blankLength++;
}
originalLength++;
}
int newLength = originalLength + 2*blankLength;
if (originalLength == 0 || newLength>a.length) {
return;
}
for (int i=originalLength-1, j=newLength-1; i>=0 && j>i; i--) {
if (a[i] == ' ') {
a[j--] = '0';
a[j--] = '2';
a[j--] = '%';
} else {
a[j--] = a[i];
}
}
}
}
剑指offer E4 替换空格为20%
最新推荐文章于 2024-11-14 21:21:03 发布