题目:28. 找出字符串中第一个匹配项的下标 - 力扣(LeetCode)
思路/想法:
双层for循环匹配,当且仅当指向子节点时返回i
代码实现:
class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() > haystack.length()) {
return -1;
}
for (int i = 0; i < haystack.length(); i++) {
int j = 0;
int mid = i;
while (mid < haystack.length() && j < needle.length() && haystack.charAt(mid) == needle.charAt(j)) {
mid++;
j++;
}
if (j == needle.length()) {
return i;
}
}
return -1;
}
}
题目:459. 重复的子字符串 - 力扣(LeetCode)
思路/想法:
简单题暴力解。
代码实现:
class Solution {
public boolean repeatedSubstringPattern(String s) {
int len = s.length(), i = 0;
while (++i < len) {
if (len % i != 0) continue;
if (s.substring(len - i, len).equals(s.substring(0, i))) {
if (s.substring(i, len).equals(s.substring(0, len - i))) {
return true;
}
}
}
return false;
}
}