28. 实现 strStr()
题目链接 给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
解法一: 暴力解法
- 遍历haystack,遇到和needle首字母相同的字符时,开始从haystack中截取needle长度的字串
- 判断字串和目标字符串是否相等,相等返回下标,否则继续遍历
class Solution {
public int strStr(String haystack, String needle) {
int start = 0;
while (start < haystack.length()) {
// 首字母相等
if (haystack.charAt(start) == needle.charAt(0)) {
String s = "";
// haystack剩余字子串要足够截取
if (haystack.length() - start >= needle.length()) {
for (int i = start; i < needle.length() + start; i++) {
s += haystack.charAt(i);
}
if (s.equals(needle)) {
break;
}
}
}
start ++;
}
int result = start == haystack.length() ? -1 : start;
return result;
}
}
459. 重复的子字符串
题目链接 给定一个非空的字符串 s
,检查是否可以通过由它的一个子串重复多次构成。
解法:枚举法。如果一个长度为 n 的字符串 s 可以由它的一个长度为 n1 的子串 s1 重多次构成。那么一定满足以下条件
- n一定是n1的倍数
- s1一定是s的前缀,并且在前缀s1之后的每个位置上的字符s[i],一定与s[i - n1]处的字符相等;
class Solution {
public boolean repeatedSubstringPattern(String s) {
int n = s.length();
// 因为子串至少需要重复一次, 字串长度不会大于s的一半; i为子串最后一个位置的下标
for (int i = 1; i <= n / 2; ++i) {
if (n % i == 0) {
boolean result = true;
for (int j = i; j < n; ++j) {
if (s.charAt(j) != s.charAt(j - i)) {
result = false;
break;
}
}
if (result) {
return true;
}
}
}
return false;
}
}