题目链接
题目描述
思路
用vector s,t按顺序记录start和target中L和R及其位置
按顺序遍历,s[i]与t[i]的字母不同,返回false。字母同为R,原先的R不能在目标R的右边;同为L,原先的L不能在目标L左边。
代码
class Solution {
public:
bool canChange(string start, string target) {
vector<pair<char,int>> s,t;
int len=start.size();
for(int i=0;i<len;i++){
if(start[i]!='_')s.push_back(make_pair(start[i],i));
if(target[i]!='_')t.push_back(make_pair(target[i],i));
}
int len_pair=s.size();
if(t.size()!=len_pair)return false;
for(int i=0;i<len_pair;i++){
// cout<<s[i].first<<" "<<s[i].second<<" "<<t[i].first<<" "<<t[i].second<<endl;
if(s[i].first!=t[i].first)return false;
if(s[i].first=='R'&&s[i].second>t[i].second)return false;
if(s[i].first=='L'&&s[i].second<t[i].second)return false;
}
return true;
}
};
结果
优化
直接双指针遍历,不需要vector存储
class Solution {
public:
bool canChange(string start, string target) {
int len=start.size();
int pos_s=0,pos_t=0;
while(pos_s<len&&pos_t<len){
while(pos_s<len&&start[pos_s]=='_')++pos_s;
while(pos_t<len&&target[pos_t]=='_')++pos_t;
if(start[pos_s]!=target[pos_t])return false;
if(start[pos_s]=='R'&&pos_s>pos_t)return false;
if(start[pos_s]=='L'&&pos_s<pos_t)return false;
++pos_s;
++pos_t;
}
while(pos_s<len&&start[pos_s]=='_')++pos_s;
while(pos_t<len&&target[pos_t]=='_')++pos_t;
if(pos_s==len&&pos_t!=len)return false;
if(pos_t==len&&pos_s!=len)return false;
return true;
}
};
结果: