1. 程式人生 > 實用技巧 >實現strStr

實現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

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C'sstrstr() and Java'sindexOf().

Constraints:

haystack andneedle consist only of lowercase English characters.

實現程式碼

實現的關鍵就是使用substring()方法,將整個字串分成與目標字串的長度相同的小段,然後使用equals方法比較,如果有相同的,則返回開始的角標

 1
package easy; 2 3 class SolutionStr{ 4 public int strStr(String hystack,String needle){ 5 int len1 = hystack.length(); 6 int len2 = needle.length(); 7 if(len2 > len1){ 8 return -1; 9 } 10 if(len2 == 0){ 11 return 0; 12 }
13 for(int i = 0;i < len1 - len2 + 1; ++i){ 14 if(hystack.substring(i,i+len2).equals(needle)){ 15 return i; 16 } 17 } 18 return -1; 19 } 20 } 21 public class ImplstrStr { 22 public static void main(String[] args) { 23 SolutionStr solution = new SolutionStr(); 24 System.out.println(solution.strStr("leetcode","ee")); 25 } 26 }