标签:
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) { char[] hay_char = haystack.toCharArray(); char[] needle_char = needle.toCharArray(); int hay_size = hay_char.length; int needle_size = needle_char.length; if(needle_size == 0){ return 0; } int dis = hay_size-needle_size; for(int i = 0;i <= dis;i++){ if(needle_char[0] == hay_char[i]){ for(int j = 0;j < needle_size;j++){ if(hay_char[i+j]!=needle_char[j]){ break; } if(j == needle_size-1){ return i; } } } } return -1; } }
标签:
原文地址:http://www.cnblogs.com/mrpod2g/p/4267322.html