1.数组中字符串匹配
思路
主要是strstr函数,在头文件string.h里
复杂度
时间:
O
(
K
n
2
)
O(Kn^2)
O(Kn2),K为字符串长度
空间:
O
(
1
)
O(1)
O(1)
class Solution {
public:
vector<string> stringMatching(vector<string>& words) {
vector<string> res;
for (int i = 0; i < words.size(); ++i) {
for (int j = 0; j < words.size(); ++j) {
if (i != j) {
//使用strstr函数来获取子串在父串中的起始位置,返回指针指向该起始位置
if (strstr(words[j].c_str(), words[i].c_str())!= NULL) {
res.push_back(words[i]);
break;
}
}
}
}
return res;
}
};
2.查询带键的排列
思路
先初始化数字1,2,3…m-1的索引,用数组index存储。然后遍历待查数组queries,先把queries数组中元素num的下标index[num]保存到res数组中,然后看看这m个数的索引,如果比index[num]小,则要+1.最后一步要把index[num]变为0(因为移到最前面去了)
复杂度
时间:
O
(
m
k
)
,
k
=
q
u
e
r
i
e
s
.
s
i
z
e
(
)
;
O(mk),k = queries.size();
O(mk),k=queries.size();
空间:
O
(
m
)
O(m)
O(m)
class Solution {
public:
vector<int>res;
vector<int> processQueries(vector<int>& queries, int m) {
int sz = queries.size();
vector<int>index(m + 1);//索引数组
for (int i = 1; i <= m; ++i) {//对m个数的索引初始化
index[i] = i - 1;
}
for (auto& num : queries) {//遍历待查数组queries
res.push_back(index[num]);//把索引保存下来
for (int i = 1; i <= m;++i) {//m个数中索引比index[num]小的,索引+1
if (index[i] < index[num])
index[i]++;
}
index[num] = 0;//移到最前面,所以索引变0
}
return res;
}
};
3.HTML实体解析器
思路
替换对以键值对形式存储,用函数库replace处理
class Solution:
def entityParser(self, text: str) -> str:
# '&':'&'要在最后替换,否则"&gt;"会被替换成">",正确的应该是>
dic={'"':'"',''':"'",'>':'>','<':'<','⁄':'/','&':'&'}
for i in dic:
text = text.replace(i,dic[i])
return text
注意点
&:&要在最后替换
复杂度
O ( K n ) O(Kn) O(Kn),K为替换对数目,n为字符串长度
4.给N*3网格图涂色的方案数
思路
1.所有格子分为ABA和ABC两种类型
2.分类讨论
3.数学计算
class Solution {
const int N = pow(10, 9) + 7;
public:
int numOfWays(int n) {
long dp[2] = { 6,6 };//n=1时ABA类和ABC类的数量
long temp;
for (int i = 1; i < n; ++i) {
temp = dp[0];
dp[0] = (3 * dp[0] + 2 * dp[1]) % N;//更新
dp[1] = (2 * temp + 2 * dp[1]) % N;
}
return (dp[0] + dp[1]) % N;
}
};
复杂度
时间:
O
(
n
)
O(n)
O(n)
空间:
O
(
1
)
O(1)
O(1)