五月集训(第02天)——字符串
字符串
1. 500. 键盘行
思路:
参考星球兴磊大佬的hash方法,将每个字母与键盘的行数对应进行索引
class Solution {
public:
vector<string> findWords(vector<string>& words) {
// 每个字母对应的行数
int my_hash[] = {2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, 3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3};
vector<string> ans;
int n = words.size();
for (int i = 0; i < n; i++) {
int m = words[i].size(), j, first_word_line;
first_word_line = my_hash[words[i][0] >= 'a' ? (words[i][0] - 'a') : (words[i][0] - 'A')];
for (j = 1; j < m; j++) { // 判断字符串中的每个字符是否和第一字符在同一行
if (first_word_line != my_hash[words[i][j] >= 'a' ? (words[i][j] - 'a') : (words[i][j] - 'A')]) break;
}
if (j == m) ans.push_back(words[i]);
}
return ans;
}
};
2. 1160. 拼写单词
思路:
还是利用第一问的hash索引方法,记录每个字母出现的次数,进行匹配即可。注意vis数组记录每个单词前要清0。
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
// vis记录单词出现的次数
int my_hash[26], vis[26];
int n, m, len, ans_len = 0;
int j = 0;
n = words.size();
len = chars.size();
memset(my_hash, 0, sizeof(my_hash));
for (int i = 0; i < len; i++) my_hash[chars[i] >= 'a' ? (chars[i] - 'a') : (chars[i] - 'A')] ++;
for (int i = 0; i < n; i++) {
memset(vis, 0, sizeof(vis));
m = words[i].size();
for (j = 0; j < m; j++) {
int current_word = words[i][j] >= 'a' ? (words[i][j] - 'a') : (words[i][j] - 'A');
if (my_hash[current_word] && vis[current_word] < my_hash[current_word]) {
vis[current_word] ++;
} else break;
}
if (j == m) ans_len += m;
}
return ans_len;
}
};
3. 1047. 删除字符串中的所有相邻重复项
思路:
利用自动机的思想,栈顶碰到一个相同的元素就pop,不同就压栈。最后从栈底到栈顶存着的就是答案。
class Solution {
public:
string removeDuplicates(string s) {
// 利用自动机的思想,栈顶碰到一个相同的元素就pop,不同就压栈
string my_stack;
int len = s.length();
for (int i = 0; i < len; i++) {
if (my_stack.empty() || s[i] != my_stack.back()) {
my_stack.push_back(s[i]);
} else {
my_stack.pop_back();
}
}
return my_stack;
}
};
4. 1935. 可以输入的最大单词数
思路:
还是利用第一问的hash索引方法,遍历整字符串,判断每个单词中是否有坏的键出现,没有则答案计数加一。
class Solution {
public:
int canBeTypedWords(string text, string brokenLetters) {
int my_hash[26];
int n = text.size();
int m = brokenLetters.size();
int ans = 0;
memset(my_hash, 0, sizeof(my_hash));
for (int i = 0; i < m; i++) my_hash[brokenLetters[i] >= 'a' ? (brokenLetters[i] - 'a') : (brokenLetters[i] - 'A')] = 1;
for (int i = 0; i < n; i++) {
int flag = 0;
while (i < n && text[i] != ' ') {
if (my_hash[text[i] >= 'a' ? (text[i] - 'a') : (text[i] - 'A')]) {
flag = 1;
}
i ++;
}
if (!flag) ans ++;
}
return ans;
}
};
东方欲晓,莫道君行早。

浙公网安备 33010602011771号