剑指OFFER 面试题5(字符串):替换空格 (JAVA)
作者:互联网
从后往前移动,每个字符仅移动一次,时间复杂度O(n)。
package codingquestions;
public class ReplaceBlank {
public static String replacespaces(String str) {
if (str==null || str.length() <=0)
return null;
int spacenum=0;
for (int i=0;i<str.length();i++) {
if (str.charAt(i)==' ') {
spacenum++;
}
}
int oldstrlen=str.length();
int newstrlen=str.length()+2*spacenum;
int oldindex=oldstrlen-1;
int newindex=newstrlen-1;
StringBuffer str1 = new StringBuffer(str);// convert string to StringBuffer
str1.setLength(newstrlen);
while (oldindex>=0 && newindex>oldindex) {
if (str1.charAt(oldindex)==' ') {
str1.setCharAt(newindex--, '0');
str1.setCharAt(newindex--, '2');
str1.setCharAt(newindex--, '%');
}else {
str1.setCharAt(newindex--, str1.charAt(oldindex));
}
oldindex--;
}
return str1.toString();
}
public static void main(String[] args) {
String str = "We are happy forever.";
String result = replacespaces(str);
System.out.println(result);
}
}
标签:oldindex,面试题,JAVA,String,OFFER,str1,str,setCharAt,newindex 来源: https://blog.csdn.net/weixin_45405128/article/details/97680014