今天继续刷牛客真题,找出最少变换的次数,使得排序为红绿。
分析:
通过双指针法,比较从前往后,将所有的绿变为红的次数和从后往前,将所有的红变为绿的次数,输出最小的数。
问题:
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))
博客围绕刷牛客真题展开,要找出使排序为红绿的最少变换次数。采用双指针法,比较从前往后把绿变红色次数和从后往前把红变绿色次数,取最小值。还提及Python中字符串Count函数可统计元素个数,并附上C++和Python代码。
4万+

被折叠的 条评论
为什么被折叠?



