题目
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
思路分析
阅读题目可是,其实问题要求的就是字符串的模式匹配问题。
可以用三种解法:
1.直接调用Java中String类中自带的方法haystack.indexOf(needle);可以直接判断一个字符串中是否包含另一个字符串。
2.直接求解法。比较简单,注意的是对特殊输入的判断处理,需要用到".equals(str)",而不是str==null。参考
直接调用String类方法:
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
直接求解法:
class Solution {
public int strStr(String haystack, String needle) {
if("".equals(haystack)&&"".equals(needle))
return 0;
else if("".equals(haystack) && !"".equals(needle))
return -1;
else if(!"".equals(haystack) && "".equals(needle))
return 0;
int len1=haystack.length();
int len2=needle.length();
if(len1<len2)
return -1;
int i=0,j,k;
while(i<len1){
int tmp=len1-i;
if(len1-i>=len2){
for(j=0,k=i;j<len2;j++,k++){
if(needle.charAt(j)!=haystack.charAt(k)){
break;
}
}
if(j==len2)
return i;
i++;
}
else
return -1;
}
return -1;
}
}
本文介绍了一种在Java中实现字符串匹配的方法,提供了两种解决方案:一种是直接使用Java内置的String类方法,另一种是通过手动实现字符串匹配算法。
442

被折叠的 条评论
为什么被折叠?



