Why is this code so slow.


  • 0
    Z
    public class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack.length()<needle.length()) return -1;
        if(needle.length() == 0) return 0;
        int slow=0,fast=0;
        while(fast<haystack.length()){
            if(slow>haystack.length()-needle.length()) break;
            if(haystack.charAt(fast) == needle.charAt(fast-slow)) fast++;
            else{
                slow++;
                fast=slow;
            }
            if(fast-slow==needle.length()) return slow;
        }
        return -1;
    }
    }
    

    Above is my code, which used two pointers. Why is it so slow.


Log in to reply
 

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