Any suggestions? How can I improve it? I tried using only one for loop


  • 0
    A

    I tried few variations. This one was accepted. I can probably reduce the number of comparisons even further. Any suggestions would be more than welcome. Thanks

     public int strStr(String haystack, String needle) {
            if (needle.length() == 0) return 0;
     		if (needle.length() > haystack.length()) return -1;
     		
     		int j = 0;
     		for (int i = 0; i < haystack.length(); i++) {
     		    
                if (haystack.charAt(i) == needle.charAt(j)) {
                    j++;
                    if ( j == needle.length()) return (i - j +1);
                }
                else {
                    i = i - j;
                    j = 0;
                }
     		}
     		
     		return -1;
        }

  • 0
    2

    the simplest solution
    haha!

    public class Solution {
    public int strStr(String haystack, String needle) {
    return haystack.indexOf(needle);
    }
    }


Log in to reply
 

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