Simple Java method using substring


  • 0
    N
    public class Solution {
        public int strStr(String haystack, String needle) {
            if(needle.length()==0)return 0;
            else if(haystack.length()<needle.length()){
                return -1;
            }
           
            
            for(int i = 0;i <= haystack.length()-needle.length();i++){
                if(haystack.substring(i,i+needle.length()).equals(needle)){
                    return i;
                }
            }
            return -1;
        }
    }
    

Log in to reply
 

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