Shortest 4ms c++ solution


  • 7
    A
    class Solution {
    public:
        int strStr(string haystack, string needle) {
        int i = 0, j = 0, count = 0;
    	if (haystack.size() == 0 && needle.size() == 0 || needle.size() == 0) return 0;
    
    	while (i < haystack.size())
    	{
    		count++;
    		if (haystack[i++] != needle[j++]) { j = 0; i=i-count+1;count = 0; }
    		if (j == needle.size()) return i - count;
    	}
    	return -1;
        }
    };

  • 0
    1

    I think your code is a brutal force algorithm


Log in to reply
 

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