今天继续刷牛客真题,找出最少变换的次数,使得排序为红绿。
分析:
通过双指针法,比较从前往后,将所有的绿变为红的次数和从后往前,将所有的红变为绿的次数,输出最小的数。
问题:
1、Python中字符串的Count函数可以统计元素的个数;
附上C++代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
cin>>s;
int n=s.length();
int sum=0,temp=0;
for(int i=0;i<n;i++)
{
if(s[i]=='G')
sum++;
else
temp=min(sum,temp+1);
}
cout<<temp<<endl;
return 0;
}
附上Python代码:
s=input()
re=[]
for i in range(len(s)):
re.append(s[:i].count('G')+s[i:].count('R'))
print(min(re))