【发布时间】: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