1 strStr
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
二 分析
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 。
如果用jdk的字符串
class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
if(haystack.contains(needle) ){
int num =-1;
num = haystack.indexOf(needle);
return num;
}else{
return -1;
}
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions forImplement strStr().
Memory Usage: 36.8 MB, less than 100.00% of Java online submissions forImplement strStr().
如何自己实现呢?
2.1 暴力循环
逐个比对haystack 与needle字符,不相等就break。
class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
int i,j;
for( i=0;i<haystack.length()- needle.length()+1;i++ ){
for( j=0; j<needle.length();j++ ){
if(haystack.charAt(i+j )!= needle.charAt(j)){
break;
}//
}// j
if(j == needle.length()){
return i;
}
}//i
return -1;
}
}
Runtime: 2 ms, faster than 52.85% of Java online submissions for Implement strStr().
Memory Usage: 37.1 MB, less than 99.53% of Java online submissions forImplement strStr().
时间复杂度是O(MN).
2.2 jdk 的实现
public static void main(String[] args) {
// TODO Auto-generated method stub
int num = strStr("hello","c");
System.out.println(num);
num = strStr("aaaa","bba");
System.out.println(num);
}
public static int strStr(String haystack, String needle) {
return indexOf(haystack.toCharArray(), 0, haystack.toCharArray().length,
needle.toCharArray(), 0, needle.toCharArray().length, 0);
}
static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount, int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
jdk 是先找第一个字符,找到后,就会再遍历剩余的target字符串。
Runtime: 1 ms, faster than 67.49% of Java online submissions for Implement strStr().
Memory Usage: 37.1 MB, less than 100.00% of Java online submissions for Implement strStr().
写的很巧妙,我自己试了下,遍历其余字符串的时候,再做普通的循环加判断更好理解些,但是提交就超时了TLE.
网上还有KMP算法,没验证。