1. 首页
  2. 软件开发
  3. day-60 字符串中最多数目的子序列

day-60 字符串中最多数目的子序列

  • 发布于 2024-09-26
  • 1 次阅读


思路
由题目可以得出,当字符串开头插入pattern[0]或在字符串结尾插入pattern[1]这两种情况中的一种所得到的子序列数目一定是最多的

解题过程
我们可以遍历字符串,统计pattern[0]的个数,每当遇到一个pattern[1]时,序列数就会加上已经遍历的pattern[0]的个数,最后加上Math.max(l,r)

Code

class Solution {

    public long maximumSubsequenceCount(String text, String pattern) {

        int len=text.length();
         int l=0,r=0;
         long ans=0;
        for(int i=0;i<len;i++){

            if(text.charAt(i)==pattern.charAt(0)){

               if(pattern.charAt(0)==pattern.charAt(1)) {

                   ans+=l;
               }
               l++;

            }else if(text.charAt(i)==pattern.charAt(1)){

               r++;
               ans+=l;
            }
        }
        return ans+Math.max(l,r);
    }
}

作者:菜卷
链接:https://leetcode.cn/problems/maximize-number-of-subsequences-in-a-string/solutions/2930151/zi-fu-chuan-zhong-zui-duo-shu-mu-de-zi-x-0bna/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文链接: https://blog.csdn.net/qq_53568730/article/details/142530292