Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

28. Implement strStr() #12

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public int strStr(String haystack, String needle) { int haystack_len = haystack.length(); int needle_len = needle.length(); if(haystack_len < needle_len) return -1; if(haystack_len == 0) return 0; for(int i = 0; i < haystack_len - needle_len + 1; i++) { //因为haystack中的一部分和needle中的一部分相同,所以只小于他们的差值即可 int flag = i; int j; for(j = 0; j < needle_len; j++) { if(haystack.charAt(flag) == needle.charAt(j)) { flag ++; continue; } else { break; } } if(j == needle_len) return i; } return -1; } }