第一遍的ac代码
class Solution {
public:
long long maximumSubsequenceCount(string text, string pattern) {
long long int na=0,nb=0;
for(int i=0;i<text.length();i++)
{
if(text[i]==pattern[0])
{
na+=1;
}
if(text[i]==pattern[1])
{
nb+=1;
}
}
if(pattern[0]==pattern[1])
{
long long re=(na+1)*na/2;
return re;
}
int maxab=max(na,nb);
long long res=0;
res+=maxab;
for(int i=0;i<text.length();i++)
{
if(text[i]==pattern[0])
{
res+=nb;
}
if(text[i]==pattern[1])
{
nb-=1;
}
}
return res;
}
};
改良版本1,优化了循环次数
class Solution {
public:
long long maximumSubsequenceCount(string text, string pattern) {
long long int na=0,nb=0;
for(int i=0;i<text.length();i++)
{
if(text[i]==pattern[1])
{
nb+=1;
}
}
if(pattern[0]==pattern[1])
{
return (nb+1)*nb/2;
}
long long res=0;
long long maxab=max(na,nb);
for(int i=0;i<text.length();i++)
{
if(text[i]==pattern[0])
{
res+=nb;
na+=1;
}
if(text[i]==pattern[1])
{
nb-=1;
}
}
maxab=max(maxab,na);
res+=maxab;
return res;
}
};
改良版本2,依据官解思路,改善了计数次序
class Solution {
public:
long long maximumSubsequenceCount(string text, string pattern) {
long long int na=0,nb=0;
long long res=0;
for(int i=0;i<text.length();i++)
{
if(text[i]==pattern[0])
{
na+=1;
}
if(text[i]==pattern[1])
{
nb+=1;
res+=na;
}
}
if(pattern[0]==pattern[1])
{
return (nb+1)*nb/2;
}
long long maxab=max(na,nb);
res+=maxab;
return res;
}
};
改变a,b的判断次序,去掉一个if语句。
class Solution {
public:
long long maximumSubsequenceCount(string text, string pattern) {
long long na=0,nb=0;
long long res=0;
for(int i=0;i<text.length();i++)
{
if(text[i]==pattern[1])
{
nb+=1;
res+=na;
}
if(text[i]==pattern[0])
{
na+=1;
}
}
return res+max(na,nb);
}
};
官方题解
class Solution {
public:
long long maximumSubsequenceCount(string text, string pattern) {
long long res = 0;
int cnt1 = 0, cnt2 = 0;
for (char c: text) {
if (c == pattern[1]) {
res += cnt1;
cnt2++;
}
if (c == pattern[0]) {
cnt1++;
}
}
return res + max(cnt1, cnt2);
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/maximize-number-of-subsequences-in-a-string/solutions/2921910/zi-fu-chuan-zhong-zui-duo-shu-mu-de-zi-x-iv6p/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
补充知识点
for (char c: text)
增强型for循环,相当于
for( int i = 0; i < s.length(); i++)
{
s[i]....
}
使用
for (char c : s)
时会复制一个s字符串再进行遍历操作,而使用
for (char& c : s)
时直接引用原字符串进行遍历操作。由于复制一个字符串花费了大量的时间,所以第二种解法要快于第一种解法。