https://oj.leetcode.com/problems/implement-strstr/
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路:
很简单,因为诸如KMP之类的算法已经完全想不起是如何解的了,暴力解法。
这里需要注意循环到haystack.length() - needle.length()就可以了,因为剩下的长度已经比子字符串要小。
public class Solution { public int strStr(String haystack, String needle) { if(needle.length() == 0){ return 0; } for(int i = 0; i < haystack.length() - needle.length() + 1; i++){ if(haystack.charAt(i) == needle.charAt(0)){ boolean flag = true; for(int j = 0; j < needle.length(); j++){ // if(i + j > haystack.length() - 1){ // flag = false; // break; // } if(needle.charAt(j) != haystack.charAt(i + j)){ flag = false; break; } } if(flag){ return i; } }else{ continue; } } return -1; } }
原文:http://www.cnblogs.com/NickyYe/p/4280573.html