Simple for loop calling String.indexOf method with 2ms


  • 0
    J

    I don't know why this is tagged as 'Dynamic Programming' but I found very simple solution that keeps calling String.indexOf(char, from index) as follows. If we can find each character in source string from target string by ascending order, it means the source string is a subsequence of the target string.

    public boolean isSubsequence(String s, String t) {
            if (s == null || t == null || s.length() > t.length()) {
                return false;
            }
    
            int index = 0;
            for (char c :s.toCharArray()) {
                index = t.indexOf(c, index);
                if (index == -1) {
                    return false;
                }
                index++;
            }
            return true;
        }
    

Log in to reply
 

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