5line Java 3ms


  • 1
    D

    Not sure why others are using really complex solutions..

    public class Solution {
        public boolean isSubsequence(String s, String t) {
            for(int i = 0, preIdx = -1; i < s.length() ; i++) {
                preIdx = t.indexOf(s.charAt(i), preIdx+1);
                if(preIdx < 0) return false;
            }
            return true;
        }
    }
    
    

  • 0

    @dongguader A very straight forward solution! I have the same idea but different implementation, which takes 28ms - way too high time that yours.
    I don't understand why but suspect it has something to do with the String's charAt() function. Here is my code for your reference.

    public class Solution {
        public boolean isSubsequence(String s, String t) {
            int i=-1, j=-1;
            while(++i<s.length()){
                while(++j<t.length() && t.charAt(j)!=s.charAt(i)) ;//i and j will point to the same char if any
                if(j==t.length()) return false;
            }
            return true;
        }
    }
    

  • 0

    Just for the record if any one have the same query - charAt() performs much worse than indexOf() in Java. Please refer to:
    https://discuss.leetcode.com/topic/57205/java-only-2ms-much-faster-than-normal-2-pointers


Log in to reply
 

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