[LeetCode]28、 Implement strStr()

题目描述:

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

 

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

思路:

子串匹配。返回子串在母串的位置。
 判定方式:
 子串为空,则返回0
 如果子串长大于母串长,则false
 遍历母串,不需要遍历整个母串,只要剩下的长度与子串相等的位置即可。对每个字符都遍历子串,不相等则break。直到遍历的长度等于子串长,
 则表示找到了子串的位置,返回i的值即开始比较的初始位置
 m = 母串长, n = 子串长, i表示母串中正在遍历的位置,j 表示已经比较了的长度
 逐字符读取String,使用charAt方法

 1 public class Solution28 {
 2     public int strStr(String haystack, String needle) {
 3         int m = haystack.length();
 4         int n = needle.length();
 5         if(n == 0) return 0;
 6         if(m < n) return -1;
 7         for(int i = 0; i <= m-n; i++){
 8             int j;
 9             for(j = 0 ; j < n; j++){
10                 if(haystack.charAt(i+j) != needle.charAt(j)) break;
11             }
12             if(j == n) return i;
13         }
14         return -1;
15     }
16     public static void main(String[] args) {
17         // TODO Auto-generated method stub
18         //String haystack = "hello";
19         //String needle = "ll";
20         String haystack = "aaa";
21         String needle = "";
22         Solution28 solution28 = new Solution28();
23         System.out.println(solution28.strStr(haystack, needle));
24     
25         
26     }
27 
28 }

 

posted @ 2017-12-29 16:00  zlz099  阅读(139)  评论(0编辑  收藏  举报