Use .toCharArray() instead of charAt()


  • 1

    It seems converting the string to char[] is much faster than just using charAt(). Using the same code below with char[] (78%) and charAt() (5%).

    public boolean isSubsequence(String s, String t) {
            if (s.length() == 0 || (s.length() == 0 && t.length() == 0)) return true;
            if (s.length() != 0 && t.length() == 0) return false;
            char[] sa = s.toCharArray();
            char[] ta = t.toCharArray();
            int i = 0, j = 0;
            while (i < ta.length) {
                if (ta[i] == sa[j]) { j++; i++; }
                else i++;
                if (j == sa.length) return true;
                if (i == ta.length && j != sa.length) return false;
            }
            return false;
        }
    

Log in to reply
 

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