题目链接:https://leetcode.com/problems/implement-strstr/description/
题目大意:字符串匹配,从字符串中,找到给定字符串第一次出现的位置下标,并返回。
法一:暴力,两个for循环,逐一比较每一个可能的字符串,一旦找到,则返回。代码如下(耗时508ms->10ms):
1 public int strStr(String haystack, String needle) { 2 int res = -1, len_h = haystack.length(), len_n = needle.length(); 3 if(len_n == 0) { 4 return 0; 5 } 6 //此处优化点:i <= len_h - len_n,当主字符串中字符个数已经过小时,则不需要再遍历了 7 for(int i = 0; i <= len_h - len_n; i++) { 8 //可能有当前字符串 9 if(len_n != 0 && haystack.charAt(i) == needle.charAt(0)) { 10 int k = i + 1, j = 1; 11 boolean flag = true; 12 for( ; j < len_n && k < len_h; j++) { 13 if(haystack.charAt(k++) != needle.charAt(j)) { 14 flag = false; 15 break; 16 } 17 } 18 if(flag == true && j == len_n) { 19 res = i; 20 break; 21 } 22 } 23 } 24 return res; 25 }