Loading

LeetCode记录之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.

实现strStr()。

返回haystack中第一次出现针的索引,如果针不是haystack的一部分,则返回-1。

 

 1 int len=0;
 2         if("".equals(needle))    //匹配字符串为空直接返回0
 3             return 0;
 4         if("".equals(haystack)||haystack.length()<needle.length())    //待匹配字符串为空或匹配字符串长度过长
 5             return -1;
 6         for (int i = 0; i < haystack.length() - needle.length()+1; i++) {//利用遍历思想,每次取出匹配字符串长度的字符串来进行匹配比较
 7             String str = haystack.substring(i, needle.length()+i);
 8             if (str.equals(needle)){
 9                 len=i;
10                 break;
11             }
12             else
13                 len=-1;
14         }
15         return len;

 

posted @ 2017-09-07 09:39  xpang0  阅读(221)  评论(0编辑  收藏  举报