糖醋里脊

有召唤,爱自由.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Implement strStr()

Posted on 2015-08-23 17:26  糖醋里脊er  阅读(139)  评论(0)    收藏  举报

Implement strStr().

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

判断一个字符串是不是另一个的子字符串

 1 public class Solution {
 2     public int strStr(String haystack, String needle) {
 3           if(haystack.length()==0&&needle.length()==0) return  0;
 4          if(needle.length()==0) return 0;
 5          if(haystack.length()<needle.length()) return -1;
 6          int i,j;
 7            for(i=j=0;i<haystack.length()&&j<needle.length();)
 8            {
 9                 if(haystack.charAt(i)==needle.charAt(j))
10                 {
11                     ++i;
12                     ++j;
13                 }
14                 else
15                 {
16                     i=i-j+1;//回溯
17                     j=0;
18                 }
19            }
20            return j!=needle.length()?-1:i-j;
21     }
22 }