题目:返回字符串位置
eg. Input: haystack = “hello”, needle = “ll” Output: 2
Input: haystack = “aaaaa”, needle = “bba” Output: -1
思路:拆分成needle长度的字符,然后比较相同长度的字符串和needle
注意:字符串可以直接像数组一样操作
class Solution {
public int strStr(String haystack, String needle) {
int len1=haystack.length();
int len2=needle.length();
if(len1<len2)
return -1;
if(len2==0)
return 0;
for (int i = 0; i <= len1 - len2; i++) {
boolean flag = true;
for (int j = 0; j < len2; j++) {
//System.out.println(i + " " + j);
if (haystack.charAt(i + j) != needle.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
return i;
}
}
return -1;
}
}