1.简介
当涉及到字符串的算法题时,常见的题型包括字符串匹配、字符串操作、字符串解析等。
- 字符串匹配:给定一个文本串和一个模式串,判断模式串是否在文本串中出现。
- 最长公共子序列:给定一个文本串和一个模式串,判断模式串是否在文本串中出现。
- 最长回文子串:给定一个文本串和一个模式串,判断模式串是否在文本串中出现。
- 字符串解析与转换:对给定的字符串进行解析和转换,例如将表达式字符串计算得出结果,或者解析特定格式的字符串。
- 字符串排列和组合:生成给定字符串的所有排列或组合。
2.示例
字符串解码
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string]
,表示其中方括号内部的 encoded_string
正好重复 k
次。注意 k
保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k
,例如不会出现像 3a
或 2[4]
的输入。
示例 1:
输入:s = "3[a]2[bc]" 输出:"aaabcbc"
示例 2:
输入:s = "3[a2[c]]" 输出:"accaccacc"
示例 3:
输入:s = "2[abc]3[cd]ef" 输出:"abcabccdcdcdef"
示例 4:
输入:s = "abc3[cd]xyz" 输出:"abccdcdcdxyz"
-
栈解
class Solution {
public:
string decodeString(string s) {
string ans;
stack<pair<int, int>> stk;
int count = 0;
for (auto x : s) {
if (isdigit(x))
count = 10 * count + (x - '0');
else if (x == '[') {
stk.push({count, ans.size()});
count = 0;
}
else if (isalpha(x))
ans += x;
else if (x == ']') {
int n = stk.top().first;
string str = ans.substr(stk.top().second, ans.size() - stk.top().second);
for (int i = 0; i < n - 1; i++) {
ans += str;
}
stk.pop();
}
}
return ans;
}
};
字符串的最大公因子
对于字符串 s
和 t
,只有在 s = t + t + t + ... + t + t
(t
自身连接 1 次或多次)时,我们才认定 “t
能除尽 s
”。
给定两个字符串 str1
和 str2
。返回 最长字符串 x
,要求满足 x
能除尽 str1
且 x
能除尽 str2
。
示例 1:
输入:str1 = "ABCABC", str2 = "ABC" 输出:"ABC"
示例 2:
输入:str1 = "ABABAB", str2 = "ABAB" 输出:"AB"
示例 3:
输入:str1 = "LEET", str2 = "CODE" 输出:""
- 枚举
class Solution {
bool check(string t,string s){
int lenx = (int)s.length() / (int)t.length();
string ans = "";
for (int i = 1; i <= lenx; ++i){
ans = ans + t;
}
return ans == s;
}
public:
string gcdOfStrings(string str1, string str2) {
int len1 = (int)str1.length(), len2 = (int)str2.length();
string T = str1.substr(0, __gcd(len1,len2)); // __gcd() 为c++自带的求最大公约数的函数
if (check(T, str1) && check(T, str2)) return T;
return "";
}
};
- 数学
class Solution {
public:
string gcdOfStrings(string str1, string str2) {
if(str1+str2 != str2 +str1)
return "";
return str1.substr(0,__gcd(str1.length(),str2.length()));
}
};