剑指offer第四题,将空格替换为%20,一开始的实现
package com.zjy.sword2offer;
public class SpaceReplace {
public static String replace(String a){
if(a==null||a.length()==0)
return null;
int count = 0;
int originalLen = a.length();
for(int i=0;i<originalLen;i++)
{
if(a.charAt(i)==' ')
count++;
}
int newLen = originalLen + count*2;
int pOriginal = originalLen-1;
int pNew = newLen-1;
StringBuffer sb = new StringBuffer(newLen);
while(pOriginal>=0 && pNew>pOriginal)
{
if(a.charAt(pOriginal)!=' ')
{
sb.insert(pNew--, a.charAt(pOriginal));
}
else
{
sb.insert(pNew-2, "%20");
pNew -= 2;
pNew--;
}
pOriginal--;
}
return sb.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "I am happy.";
String res = replace(str);
System.out.println(res);
}
}
一直报错如下
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at java.lang.AbstractStringBuilder.insert(Unknown Source)
at java.lang.StringBuffer.insert(Unknown Source)
at com.zjy.sword2offer.SpaceReplace.replace(SpaceReplace.java:27)
at com.zjy.sword2offer.SpaceReplace.main(SpaceReplace.java:44)
猜想出错的原因在于StringBuffer初始化后内容是空的,不能直接从后边用setCharAt()或者insert()插入数据,否则报错,后来换了一个方式ok了,如下
package com.zjy.sword2offer;
public class SpaceReplace {
public static String replace(String a){
if(a==null||a.length()==0)
return null;
int count = 0;
int originalLen = a.length();
for(int i=0;i<originalLen;i++)
{
if(a.charAt(i)==' ')
count++;
}
int newLen = originalLen + count*2;
int pOriginal = originalLen-1;
int pNew = newLen-1;
StringBuffer sb = new StringBuffer(newLen);
while(pOriginal>=0 && pNew>=0)
{
char ch = a.charAt(pOriginal);
if(ch!=' ')
{
sb.append(ch);
}
else
{
sb.append("02%");
}
pOriginal--;
}
return sb.reverse().toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "I am happy.";
String res = replace(str);
System.out.println(res);
}
}