题目要求,判断target字符串是否是给出的字符串的子串。
思路:运用字符串函数,substring(start,end+1),从给出的数组中提取跟target字符串长度一样的子串,用equals判断两个字符串是否相等
class Solution{
public int strStr(String haystack,String needle){
int hay_len=haystack.length();
int nee_len=needle.length();
int limit=hay_len-nee_len;
if(hay_len<0)
return -1;
for(int i=0;i<=limit;i++){
if(needle.equals(haystack.substring(i,i+nee_len){
return i;
}
}
return -1;
}
}
Python:
class Solution(Object):
def strStr(self,haystack,needle):
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)]==needle:
return i
return -1