[leedcode 28] Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

public class Solution {
    public int strStr(String haystack, String needle) {
        //此题解法,外层循环haystack,每一位与needle进行比较。两层for循环
        //注意flag需要重新置位
        //注意外层循环的范围,不需要循环到最后一位,只要循环到倒数第二个字符串长度即可
        if(needle.length()==0) return 0;
        if(haystack.length()==0) return -1;
         
        int lenH=haystack.length();
        int lenN=needle.length();
        boolean flag=true;
        for(int i=0;i<=lenH-lenN;i++){
            if(haystack.charAt(i)==needle.charAt(0)){
                 /* int temp=i+1;
                  for(int j=1;j<lenN;j++){
                      if(haystack.charAt(temp)!=needle.charAt(j)){
                           flag=false;
                          break;
                         
                      }else{
                          temp++;
                      }
                  }*/
                  for(int j=0;j<lenN;j++){
                      if(haystack.charAt(j+i)!=needle.charAt(j)){
                          flag=false;
                          break;
                          
                      }
                      
                  }
                  ////////////////
                  if(flag){
                      return i;
                  }
                  flag=true;//置位
           
            }
  
        }
        return -1;
      
    }
}

 

posted @ 2015-07-08 21:58  ~每天进步一点点~  阅读(119)  评论(0编辑  收藏  举报