简体   繁体   中英

What is the time complexity of lastIndexOf in java?

What is the time complexity of the lastIndexOf in java for using it with String s. Suppose: int t= s.lastIndexOf(c); where s is some String and c is s.charAt(0)

As soon as String is implemented as char array it is O(n).

public int lastIndexOf(int ch, int fromIndex) {
    if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
        // handle most cases here (ch is a BMP code point or a
        // negative value (invalid code point))
        final char[] value = this.value;
        int i = Math.min(fromIndex, value.length - 1);
        for (; i >= 0; i--) {
            if (value[i] == ch) {
                return i;
            }
        }
        return -1;
    } else {
        return lastIndexOfSupplementary(ch, fromIndex);
    }
}

For String.lastIndexOf(int) it's linear - O(n) .

You at least need to iterate over the whole character sequence, end to start.

And that's what Java does.

Worst case: "abbbbbbbbbb".lastIndexOf('a')

For String.lastIndexOf(String) it's O(n*m) where n is input length and m is parameter length.

In this case, Java iterates end to start and wherever it finds matching last character of the needle it tries to match preceding characters on both sides as well.

Look at the implementation of this method. In both code branches it contain simple iteration over string's internal array:

 int i = Math.min(fromIndex, value.length - 1);
 for (; i >= 0; i--) {
      if (value[i] == ch) {
             return i;
      }
 }

Hence complexity is just O(n) , ie linear.

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