简体   繁体   中英

Java StringBuilder Delete Last Occurance of Character Efficiently

What is the most efficient way to delete the last occurance of a char from a StringBuilder ?

My current solution is O(N) , but I feel like this problem can be solved in constant time.

public StringBuilder deleteLastOccurance(StringBuilder builder, char c) {        
    int lastIndex = builder.lastIndexOf(String.valueOf(c));
    if (lastIndex != -1) {
        builder.deleteCharAt(lastIndex); // O(N)
    }
    return builder;
}

In the end it will be an O(n) time no matter what. There is no other way to determine the last character without checking all the way to the end.

Even internal java API methods will have the same underlying implementation.

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