1. 题目
来源:https://tianchi.aliyun.com/oj/164423301311799378/184808348725744276
2. 解题
class Solution {
public:
/**
* @param s: a string
* @param t: a string
* @param n: max times to swap a 'l' and a 'r'.
* @return: return if s can transform to t.
*/
bool LRString(string &s, string &t, int n) {
// write your code here.
if(s.size() != t.size())
return false;//长度不等不行
int ls = 0, rs = 0, lt = 0, rt = 0;
vector<int> sLidx, tLidx;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == 'l')
{
ls++;
sLidx.push_back(i);
}
else
rs++;
}
for(int i = 0; i < t.size(); i++)
{
if(t[i] == 'l')
{
lt++;
tLidx.push_back(i);
}
else
rt++;
}
if(ls != lt || rs != rt)
return false;// lr字符数量不等不行
int sw = 0;
for(int i = 0; i < sLidx.size(); i++)
{
if(sLidx[i] == tLidx[i])
continue;
else if(sLidx[i] < tLidx[i])
return false;// l 的位置只能往左,不可能做到
else
sw += sLidx[i] - tLidx[i];// 要移动的距离
}
return sw <= n;
}
};
50ms C++
我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!