一个本硕双非的小菜鸡,备战24年秋招,计划刷完卡子哥的刷题计划,加油!
推荐一手卡子哥的刷题网站,感谢卡子哥。代码随想录
力扣344反转字符串
Note:
class Solution {
public:
void reverseString(vector<char>& s) {
int m = s.size() - 1;
for (int i = 0, j = m; i < j; i++, j--) {
swap(s[i], s[j]);
}
}
};
541. 反转字符串 II
Note:通过使用reverse方法,很容易。
class Solution {
public:
string reverseStr(string s, int k) {
for (int i = 0; i < s.size(); i += (2*k)) {
if (i + k <= s.size())
reverse(s.begin() + i, s.begin() + i + k);
else
reverse(s.begin() + i, s.end());
}
return s;
}
};
剑指 Offer 05. 替换空格
Note:扩展空间,双指针从尾部遍历。
class Solution {
public:
string replaceSpace(string s) {
int count = 0;
int m = s.size();
for (int i = 0; i < m; i++) {
if (s[i] == ' ')
count++;
}
s.resize(s.size() + count * 2);
int n = s.size();
for (int i = n - 1, j = m - 1; j < i; i--, j--) {
if (s[j] != ' ')
s[i] = s[j];
else {
s[i] = '0';
s[i - 1] = '2';
s[i - 2] = '%';
i -= 2;
}
}
return s;
}
};
151. 反转字符串中的单词
Note:做到现在感觉自己进步很大,可以尝试自我编写了。
class Solution {
public:
void removeExtraSpaces(string& s) {
int slow = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] != ' ') {
if (slow != 0)
s[slow++] = ' ';
while (i < s.size() && s[i] != ' ')
s[slow++] = s[i++];
}
}
s.resize(slow);
}
void reserse(string& s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--)
swap(s[i], s[j]);
}
string reverseWords(string s) {
removeExtraSpaces(s);
reserse(s, 0, s.size() - 1);
int start = 0;
for (int i = 0; i <= s.size(); i++) {
if (i == s.size() || s[i] == ' ') {
reserse(s ,start, i - 1);
start = i + 1;
}
}
return s;
}
};
剑指 Offer 58 - II. 左旋转字符串
Note:三重旋转
class Solution {
public:
string reverseLeftWords(string s, int n) {
reverse(s.begin(), s.begin() + n);
reverse(s.begin() + n, s.end());
reverse(s.begin(), s.end());
return s;
}
};
28. 找出字符串中第一个匹配项的下标
Note:初试KMP,主要难点在于next数组的构造。这里推荐卡子哥的解答。
class Solution {
public:
void getNext(int* next, const string& s) {
int j = -1;
next[0] = j;
for (int i = 1; i < s.size(); i++) {
while (j >= 0 && s[i] != s[j + 1])
j = next[j];
if (s[i] == s[j + 1])
j++;
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) return 0;
int next[needle.size()];
getNext(next, needle);
int j = -1;
for (int i = 0; i < haystack.size(); i++) {
while (j >= 0 && haystack[i] != needle[j + 1]) {
j = next[j];
}
if (haystack[i] == needle[j + 1])
j++;
if (j == (needle.size() - 1))
return (i - needle.size() + 1);
}
return -1;
}
};
459. 重复的子字符串
Note:KMP二连,尝试了三种解决办法,卡子哥推荐的s+s真的很巧妙。
class Solution {
public:
void getNext (int* next, const string& s) {
next[0] = -1;
int j = -1;
for (int i = 1; i < s.size(); i++) {
while (j >= 0 && s[i] != s[j + 1])
j = next[j];
if (s[i] == s[j + 1])
j++;
next[i] = j;
}
}
bool repeatedSubstringPattern(string s) {
if (s.size() == 0) return false;
int next[s.size()];
getNext(next, s);
int len = s.size();
if (next[len - 1] != -1 && len % (len - (next[len - 1] + 1)) == 0)
return true;
return false;
}
};
字符串给我印象最深的就是KMP了,这个算法真的很巧妙,以后需多看多学多练,争取早日成为算法大佬!