简体   繁体   中英

Removing a character from a string efficiently

I wrote this function as part of interview practice. This method removes a character from a given string.

I was wondering how I could make this code more efficient when it comes to runtime/space. I think my code is O(n) and I'm not sure if I can increase the efficiency. However, perhaps using things such as StringBuffer or StringBuilder would increase it a bit? Not sure as I'm still a bit new to Java.

public static String takeOut(String str, char c) {
    int len = str.length();
    String newstr = "";
    for (int i = 0; i < len; i++) {
        if (str.charAt(i) != c) {
            newstr = newstr + str.charAt(i);
        }
    }
    return newstr;
}

Strings are immutable in Java, so your answer actually results in len number of strings being created. Which means they are copied len times, so you have O(N*N) code here. StringBuilder is definitely a better approach.

public static String takeOut(String str, char c) {
    int len = str.length();
    StringBuilder newstr = new StringBuilder();
    for (int i = 0; i < len; i++) {
        if (str.charAt(i) != c) {
            newstr.append((char)str.charAt(i));
        }
    }
    return newstr.toString();
}

A simpler approach would be to use the built in function:

public static String takeOut(String str, char c) {
    return str.replace(String.valueOf(c), "");
}

StringBuilder would definitely prevent your code from creating new strings with every iteration. Additionally, is the character to be removed contained only once in the string? Then you could break the for loop after the first match. Also, locally store the result of String#charAt to not call the method twice.

Have you tried

str.replaceAll(c,"");

? Maybe the Java-Runtime kows the fastest way of replacing (deleting)...

My suggestion to replace any char more efficiently would be:

1) Convert the String to a char[] array.

2) Run through the array, testing each character one by one and replacing it if needed and append in StringBuilder

I think this is probably the fastest performance you will get in pure Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM