Can anyone help me debug my code?


  • 0
    J
    public class Solution {
        public int strStr(String haystack, String needle) {
            
            if(haystack == null || needle == null || (needle.length() > haystack.length())) {
                return -1;
            }
            if(haystack.equals(needle)) {
                return 0;
            }
            for(int i = 0; i < haystack.length(); i++){
                int count = 0;
                //str.length(); arr.length
                for(int j = 0; j < needle.length(); j++){
                  if(haystack.charAt(i) != needle.charAt(j)) {
                     i = i - count;
                     break;
                  }else if(haystack.charAt(i) == needle.charAt(j)) {
                      count++;
                      if(count == needle.length()) {
                          return (i - needle.length() + 1);
                      }
                      if(i < haystack.length() - 1){
                          i++;
                      }
                 
                  }
                }
            }
            return -1;
        }
    }
    

  • 0
    J

    Input:
    "a"
    ""
    Output:
    -1
    Expected:
    0


Log in to reply
 

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