剑指 Offer 58 - II. 左旋转字符串
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
//法一:占用额外空间,字符串拼接
class Solution {
public:
string reverseLeftWords(string s, int n) {
int len = s.size();
string s1 = s.substr(0, n);//获得前n个字符的字符串
string s2 = s.substr(n, len - n);//获得长度为n-k的字符串
return s2 + s1;//进行拼接
}
};
//法二:不占用额外的空间
class Solution {
public:
string reverseLeftWords(string s, int n)
{
int n1 = s.size();
reverse(s.begin(), s.end());//整体反转字符串,reverse函数反转的区间是左闭右开
reverse(s.begin(), s.begin() + n1 - n);//单独反转每个字符串
reverse(s.begin() + n1 - n, s.end());
return s;
}
};
- 实现 strStr()
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
class Solution {
public:
void get_next_array(int* next, string s)//此函数是求前缀表
{
int i = 0, j = 1;
int n = s.size();
next[0] = 0;
while (j < n)
{
while (i > 0 && s[i] != s[j])//当遇到前缀不等于后缀的时候,就要寻找跟后缀前面的数相等的下一位,而前缀的前一位的next值就是那一位
{
i = next[i - 1];
}
if (s[i] == s[j])//如果前缀和后缀相等,那后缀就是i+1
{
next[j] = i + 1;
i++;
}
else
{
next[j] = 0;//如果前缀和后缀不相等,那么前缀等于0,此时对应的应该等于0
}
j++;
}
}
int strStr(string haystack, string needle) {
int len1 = haystack.size();
int len2 = needle.size();
if (len2 == 0)
{
return 0;
}
int next1[len2];
get_next_array(next1, needle);
int j = 0;
int i = 0;
for (int i = 0; i < len1; i++)
{
while (j >= 1 && haystack[i] != needle[j])//当遇到主字符串和子字符串对应的字符不等时,就应该将子字符串下标前移
{
j = next1[j - 1];
}
if (haystack[i] == needle[j])
{
j++;
}
if (j == len2)
{
return i - len2 + 1;
}
}
return -1;
}
};
KMP算法