《剑指offer》关于“替换空格”的整理(java版)

将空格替换成“abc”

方法一:
使用java的API,String.replace()方法的简单实现。
public class Main {
public static void main(String[] args) {
String s = "1 2 3 4 5 6 7 8 9 0";
s = method(s);
System.out.println(s);
}


private static String method(String s) {
// TODO Auto-generated method stub
if (s == null || s.length() <= 0) {
return null;
}
return s.replace(" ", "abc");
}
}
方法二:
使用java的API,StringBuffer.append()方法的简单实现。
public class Main {
    public static void main(String[] args) {
        String s = "1 2 3 4 5 6 7 8 9 0";
        s = method(s);
        System.out.println(s);
    }

    private static String method(String s) {
        // TODO Auto-generated method stub
        if (s == null || s.length() <= 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == ' '){
                sb.append("abc");
            }else{
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }
}
方法三:
自己编写方法,算法实现。
public class Main {
public static void main(String[] args) {
String s = "1 2 3 4 5 6 7 8 9 0";
s = method(s);
System.out.println(s);

}


private static String method(String s) {
// TODO Auto-generated method stub
if (s == null || s.length() == 0) {
return null;
}
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
count++;
}
}
int oldLen = s.length();
//扩展数组的长度
int newLen = s.length() + 2 * count;
char[] newc = new char[newLen];
System.arraycopy(s.toCharArray(), 0, newc, 0, s.length());

//定义两个游标,i指向newc数组中的当前值,j指向newc数组中初始化的值,然后从后往前初始化newc数组,直到i指向0或者j追上i。
int i = oldLen - 1, j = newLen - 1;
while (i >= 0 && i < j) {
if (newc[i] == ' ') {
newc[j--] = 'c';
newc[j--] = 'b';
newc[j--] = 'a';


} else {
newc[j--] = newc[i];
}
i--;
}
String newStr = new String(newc);
return newStr;
}


}

性能比较

把原字符串长度扩大十倍后,得到大概的运行时间如下。
方法一 方法二 方法三
27ms 9ms 5ms
注意点:
  1. String类型的变量值不能修改,为了防止产生大量字符串对象,系统在内部定义了字符串常量池。
  2. java API 的方法中包含了动态扩展数组长度的功能。
  3. 如果原字符序列的长度不够,一定要动态开辟数组空间,否则数组下标越界。
发布了10 篇原创文章 · 获赞 1 · 访问量 2325

猜你喜欢

转载自blog.csdn.net/qq_35334269/article/details/78961901