Simple java in-place


  • 0
    I
    public class Solution {
        public int strStr(String haystack, String needle) {
            if(haystack.equals(needle) || needle.isEmpty()) {
                return 0;
            }
            if(haystack.isEmpty()) {
                return -1;
            }
            
            for(int i = 0; i <= haystack.length() - needle.length(); i++) {
                if(isPrefix(needle, haystack, i)) {
                    return i;
                }
            }
            
            return -1;
        }
        
        boolean isPrefix(String prefix, String s, int start) {
            for(int i = 0; i < prefix.length(); i++) {
                if(prefix.charAt(i) != s.charAt(start + i)) {
                    return false;
                }
            }
            
            return true;
        }
    }
    

Log in to reply
 

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