budi
budi

Reputation: 6551

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;
}

Upvotes: 0

Views: 395

Answers (1)

scerrecrow
scerrecrow

Reputation: 269

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.

Upvotes: 3

Related Questions