0512刷题
LeetCode 28. 实现 strStr()
LeetCode 28. 实现 strStr()
方法1.哈希+滑动窗口法
class Solution {
public:
int strStr(string s, string p) {
int sLen = s.size(), pLen = p.size();
if (sLen < pLen) return -1;
vector<int> result;
vector<int> sCount(26);
vector<int> pCount(26);
//统计长度为pLen的字符串中,各个小写字母出现的次数
for (int i = 0; i < pLen; ++i)
{
++sCount[s[i] - 'a'];
++pCount[p[i] - 'a'];
}
//如果相等,则0符合要求
if (sCount == pCount)
{
if(s.substr(0,pLen)==p) return 0;
}
//长度为pLen的窗口向右滑动
//移出的元素个数--
//移入的元素个数++
for (int i = 0; i < sLen - pLen; ++i)
{
--sCount[s[i] - 'a'];
++sCount[s[i + pLen] - 'a'];
//相等,则push_back进result
if (sCount == pCount)
{
if(s.substr(i+1,pLen)==p) return i+1;
}
}
return -1;
}
};
基本方法同LeetCode 438. 找到字符串中所有字母异位词
方法2.滑动窗口法2
class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.size(),len2=needle.size();
//尾指针的位置由needle数组的长度确定,也就是(0+len2-1)
int head=0,tail=len2-1;
//循环结束的条件是尾指针到达haystack数组的尾部
while(tail<len1){
//判断haystack数组以head为开头,len2为长度的子串和needle数组是否相同
if(haystack.substr(head,len2)==needle) return head;
head++;
tail++;
}
return -1;
}
};
解题思路
1.定义两个指针,左指针从haystack数组的头开始,右指针的位置由needle数组的长度确定,也就是len2-1,保持窗口大小为len2
2.进入while循环,循环结束的条件是右指针到达haystack数组的结尾
3.判断haystack数组以left为开头,len2为长度的子串和needle数组是否相同,是则返回此时的left值
4.对左右两个指针做++操作,保持窗口大小
5.循环结束,代表匹配失败,返回-1
方法3.暴力解法
class Solution {
public:
int strStr(string haystack, string needle) {
int temp = 0;
int start = 0; // 最终结果
if(needle.empty()||haystack.empty())return 0;
for(int i=0;i<haystack.size();i++)
{
if(haystack[i]==needle[0])
{
start = i;
if(needle.length()>haystack.length()-i) return -1;
temp = i;
int j = 0;
for(j=0;j<needle.size();j++)
{
if(needle[j]!=haystack[temp])
{
break;
}
temp++;
}
if(j == needle.size()){
return start;
}
}
}
return -1;
}
};
LeetCode 459. 重复的子字符串
LeetCode 459. 重复的子字符串
方法一:枚举
思路与算法
如果一个长度为 nn 的字符串 ss可以由它的一个长度为 n’的子串 s’重复多次构成,那么:
1.n 一定是 n’的倍数;
2.s’一定是 s的前缀;
3.对于任意的i∈[n′,n),有 s[i] = s[i-n’].
也就是说,ss中长度为 n’的前缀就是 s’,并且在这之后的每一个位置上的字符 s[i],都需要与它之前的第 n’个字符 s[i-n’]相同。
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int n = s.size();
for (int i = 1; i * 2 <= n; ++i) {
if (n % i == 0) {
bool flag = true;
for (int j = i; j < n; ++j) {
if (s[j] != s[j - i]) {
flag = false;
break;
}
}
if (flag) {
return true;
}
}
}
return false;
}
};