链接:
2337. 移动片段得到字符串
题意:
L
可以和左边的_
交换,R
可以和右边的_
交换,求判断A是否能通过交换(不限次数)变成B
解:
观察可知,如果存在RL
,一定不能交换出LR
,所以按序遍历A和B时,除去_
,遍历到的字符需要相同
除外,判断A的L位置是否大于等于B的L(A的L通过左移变成B的L),A的R位置是否小于等于B的R即可
双指针解题
实际代码:
#include<iostream>
using namespace std;
bool canChange(string start, string target)
{int index=0,mb=0,lg=start.size();while(true){while(mb<lg && target[mb]=='_') mb++;while(index<lg && start[index]=='_') index++;if(index==mb && index==lg) break;if(target[mb]!=start[index]) return false;else{if(target[mb]=='R'){if(mb>=index){mb++;index++;}else return false;}else{if(mb<=index){mb++;index++;}else return false;}}}return true;
}
int main()
{string start,target;cin>>start>>target;bool ans=canChange(start,target);cout<<boolalpha<<ans<<endl;return 0;
}
限制:
n == start.length == target.length
1 <= n <= 105
start
和target
由字符'L'
、'R'
和'_'
组成