LeetCode打卡
一、比较含退格的字符串
- 题目:
- 题解:
class Solution {
public:
bool backspaceCompare(string s, string t) {
return rebuildStr(s)==rebuildStr(t);
}
string rebuildStr(string str){
string s;
for(const auto&pr:str){
if(pr!='#'){
s.push_back(pr);
}else if(!s.empty()){
s.pop_back();
}
}
return s;
}
};
二、区间列表的交集
- 题目
- 题解:
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
if(firstList.empty()||secondList.empty()) return vector<vector<int>>{};
int i=0,j=0;
vector<vector<int>>v;
while(i<firstList.size()&&j<secondList.size()){
int leftMax=max(firstList[i][0],secondList[j][0]);
int rightMin=min(firstList[i][1],secondList[j][1]);
if(leftMax<=rightMin){
v.push_back({leftMax,rightMin});
}
if(firstList[i][1]<secondList[j][1]){
i++;
}else{
j++;
}
}
return v;
}
};
三、找到字符串中所有字母异位词
-
题目:
-
题解:
-
方法一(暴力+哈希,超时):
int pLen=p.size();
int sLen=s.size();
if(pLen>sLen) return {};
unordered_map<char,int>mp;
for(const auto&pr:p){
mp[pr]++;
}
vector<int>index;
for(int i=0;i<sLen-pLen+1;i++){
unordered_map<char,int>copy;
for(int j=0;j<p.size();j++){
copy[s[j+i]]++;
}
if(copy==mp) index.emplace_back(i);
}
return index;
- 方法二(滑动窗口):
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
int pLen=p.size(),sLen=s.size();
if(pLen>sLen) return vector<int>();
vector<int>res;
vector<int>sCount(26);
vector<int>pCount(26);
for(int i=0;i<p.size();i++){
sCount[s[i]-'a']++;
pCount[p[i]-'a']++;
}
if(sCount==pCount) res.emplace_back(0);
for(int i=0;i<sLen-pLen;i++){
--sCount[s[i] - 'a'];
++sCount[s[i + pLen] - 'a'];
if (sCount == pCount){
res.emplace_back(i+1);
}
}
return res;
}
};