day09 打卡28. 找出字符串中第一个匹配项的下标 459. 重复的子字符串
day09 打卡28. 找出字符串中第一个匹配项的下标 459. 重复的子字符串
28. 找出字符串中第一个匹配项的下标
1.我的思路:先用list去存储每个第一位都一样的下标。然后遍历list,for循环从记住的下标开始,对比每个字符。如果都一样的话,就是需要的下标。
class Solution {
public int strStr(String haystack, String needle) {
if (needle == null || haystack == null || needle.equals("")) return -1;
List<Integer> list = new ArrayList<>();
for (int i = 0 ; i<haystack.length() ; i++) {
if (haystack.charAt(i) == needle.charAt(0)) {
list.add(i);
}
}
for (int i: list) {
boolean existSame = true;
if (needle.length() > haystack.length()-i) continue;
for (int j = i, k=0; j<haystack.length() && k<needle.length(); j++, k++) {
if (haystack.charAt(j) != needle.charAt(k)) {
existSame = false;
break;
}
}
if (existSame) return i;
}
return -1;
}
}
2.看视频的写的。视频链接
class Solution {
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0) return -1;
int[] next = new int[needle.length()];
getNext(next, needle);
int j = 0;
for (int i = 0 ; i<haystack.length() ; i++) {
while (j>0 && needle.charAt(j) != haystack.charAt(i)) {
j = next[j-1];
}
if (needle.charAt(j) == haystack.charAt(i)) {
j++;
}
if (j == needle.length()) {
return i-needle.length()+1;
}
}
return -1;
}
public void getNext(int[] next, String str) {
int j = 0 ;
next[0] = 0;
for (int i = 1; i<str.length() ; i++) {
while (j>0 && str.charAt(j) != str.charAt(i)) {
j = next[j-1];
}
if (str.charAt(j) == str.charAt(i)) {
j++;
}
next[i] = j;
}
}
}
459. 重复的子字符串
1.移动匹配
class Solution {
public boolean repeatedSubstringPattern(String s) {
String str = s + s;
return str.substring(1, str.length() - 1).contains(s);
}
}
2.kmp不太懂
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律