Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
字符串匹配问题,要注意needle 为空的情况,最简单的代码是:
public class Solution { public int strStr(String haystack, String needle) { return haystack.indexOf(needle); } }
当然这样写就没啥意义了。
完整代码:
public class Solution { public int strStr(String haystack, String needle) { int size1 = haystack.length(); int size2 = needle.length(); if(size2==0) return 0; int gap = size1-size2; for(int i=0;i<=gap;i++) { for(int j=0;j<size2;j++) { if(haystack.charAt(j+i)!=needle.charAt(j)) break; else if(j==size2-1) return i; } } return -1; } }