The reason why indexOf is faster then charAt!

  • 2
        for(int j=0; k<slen;j++) // total looped t.length() times
            if(j==tlen) return false;
            tem =
            if(s.charAt(k)==t.charAt(j)) k++;
        for(int i = 0; i < s.length();i++)//total looped s.length times
            char tempChar = s.charAt(i);
            prev = t.indexOf(tempChar,prev);
            if(prev == -1) return false;

    Many people confuse about why indexOf could solve this question in 2ms. I think the reason is following:

    If we just compare indexOf and charAt, of course, indexOf takes more time.(please read source code)

    However, in this question, if we use indexOf, it will be called s.length times, where charAt will be call t.length times.

    In the test cases, t is much larger than s which results in this 2ms solution(indexOf) vs 30ms solution(charAt).

  • 0

    Thanks. This solves my confusion.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.