實作strStr(),傳回下标數字或-1
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
1 package com.rust.TestString;
2
3 public class ImplementstrStr {
4 public static int strStr(String haystack, String needle) {
5 int index = 0;
6 int res = 0;
7 int len = haystack.length();
8 int nlen = needle.length();
9 if (haystack.equals(needle) || nlen == 0) {
10 return 0;
11 }
12 if (len < nlen) {
13 return -1;
14 }
15 if (len == 1 && haystack.equals(needle)) {
16 return 0;
17 }
18
19 for (int i = 0; i < haystack.length(); i++) {
20 if (haystack.charAt(i) == needle.charAt(0)) {
21 if (len - i < nlen) {
22 return -1;
23 }
24 index = i + 1;
25 res = i;
26 int j = 1;
27
28 while (j < needle.length()){
29 if (haystack.charAt(index) == needle.charAt(j)) {
30 index++;
31 j++;
32 } else {
33 break;
34 }
35 }
36 if (index - res == nlen) {
37 return res;
38 }
39 }
40 }
41 return -1;
42 }
43
44 public static void main(String args[]){
45 System.out.println(strStr("abc", "c"));
46 System.out.println(strStr("aadbdffad", "df"));
47 System.out.println(strStr("dbdffad", "df"));
48 System.out.println(strStr("dbdffad", ""));
49 }
50 }