【问题标题】:Print the length of maximum subsequence of '1' s打印 '1' 的最大子序列的长度
【发布时间】:2021-12-29 23:57:53
【问题描述】:
import java.util.Scanner;
class Motu
 {
    // Returns length of the longest subsequence
    // of the form 0*1*0*
    public static int longestSubseq(String s)
    {
        int n = s.length();
 

       
        int[] count_1 = new int[n + 1];
        count_1[0] = 0;
        for (int j = 1; j <= n; j++)
         {
            count_1[j] = count_1[j - 1];
            if (s.charAt(j - 1) != '0')
                 count_1[j]++;
         }
          
        // Compute result using precomputed values
        int ans = 0;
        for (int i = 1; i <= n; i++)
            for (int j = i; j <= n; j++)
                ans = Math.max(count_1[j] - count_1[i - 1] , ans);
                               
        return ans;
     }
 
    // Driver code
    public static void main(String[] args)
    {
        @SuppressWarnings("resource")
        Scanner sc=new Scanner(System.in);
        String s =sc.next();
        System.out.println(longestSubseq(s));
    }
}

我正在尝试编写一个程序来获取包含0's 和1's 的字符串中的最大序列1。但我无法弄清楚它的逻辑,我的程序在字符串中打印了许多 1,这不是我想要的输出。

Sample input:- 0011100111100
output:- 4

【问题讨论】:

  • 您应该在找到 1 时对每个字符进行迭代,当您找到 0 时开始计数,如果新计数高于前一个计数,则应重置计数器并更新“max”变量。
  • 你的 cmets 与代码无关。例如,没有 pre_count_0 和 post_count_0 变量。无论如何,我建议简化您的代码。试着想象你会如何在脑海中解决这个问题。您是否需要知道所有零子序列的长度才能知道最长的序列是什么?我想不是因为您也可以使用 1000 位数字的序列来做到这一点,并且您不会在脑海中存储每个零的子序列长度。因此,请尝试在您的代码中应用相同的逻辑。代码会更容易理解

标签: java arrays sorting sequence


【解决方案1】:

作为使用 for 循环的其他答案的替代方案:

您可以使用正则表达式将序列分成几组。接下来,如果组的长度大于之前的长度,只需遍历组并更新计数。

第一组是111,下一组是1111。因此计数将首先为 3,然后将更新为 4。

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class CountSubsequence {
     public static void main(String []args){
        String sequence = "0011100111100";
        Pattern pattern = Pattern.compile("(1+)");
        Matcher matcher = pattern.matcher(sequence);
        int count = 0;
        while (matcher.find()) {
            int currentLength = matcher.group().length();
            if (currentLength > count) count = currentLength;
        }
        System.out.println(count); // 4
     }
}

由于正则表达式的性能不高,如果您关心性能,您可能希望使用 for 循环 - 但如果您经常执行它,这很重要。

【讨论】:

    【解决方案2】:

    输入字符串可以被非1的字符分割(因此所有非1字符都被忽略并且只包含1的子序列),然后是剩余的最大长度可以使用 Stream API 找到部件:

    public static int longestSubSequence(String str, char ch) {
        return Arrays.stream(str.split("[^" + ch + "]"))
                     .mapToInt(String::length)
                     .max()
                     .orElse(0);
    }
    

    类似地,可以创建一个匹配模式,并且可以找到组的最大长度:

    public static int longestSubSequence(String str, char ch) {
        return Pattern.compile(ch + "+")
                .matcher(str)
                .results()
                .map(MatchResult::group)
                .mapToInt(String::length)
                .max()
                .orElse(0);
    }
    

    测试:

    System.out.println(longestSubSequence("00111011001111", '1')); // 4
    

    值得一提的是,输入字符串中可能存在'0'和'1'以外的字符,仅计算给定字符的子序列。

    【讨论】:

      【解决方案3】:
      public static int longestSubSequence(String str, char ch) {
          int res = 0;
          int count = 0;
      
          for (int i = 0; i < str.length(); i++) {
              count = str.charAt(i) == ch ? count + 1 : 0;
              res = Math.max(res, count);
          }
      
          return res;
      }
      

      【讨论】:

        【解决方案4】:

        你很好,但你缺少一件事:如果字符是'0':将计数器重置为零

        for (int j = 1; j <= n; j++) {
            if (s.charAt(j - 1) != '0')
                count_1[j] = count_1[j - 1] + 1;
            else
                count_1[j] = 0;
        }
        

        但这只能在一个循环中完成,用 int 计数,并跟踪最大值

        public static int longestSubseq(String s) {
            int ans = 0;
            int count = 0;
            for (char c : s.toCharArray()) {
                if (c == '1')
                    count++;
                else
                    count = 0;
        
                ans = Math.max(ans, count);
            }
            return ans;
        }
        

        【讨论】:

        • @azro 感谢您的建议,我已添加 else 语句以将计数器重置为 0。程序运行正常
        • @ScaryWombat 跟踪最长的子序列?
        猜你喜欢
        • 2021-04-28
        • 2022-07-21
        • 1970-01-01
        • 2015-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-15
        相关资源
        最近更新 更多