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));
}
}
我正在嘗試制作一個程式來獲取1包含0's&的字串中的最大序列1's。但是我無法弄清楚它的邏輯,我的程式在字串中列印了一些不是我想要的輸出的 1。
Sample input:- 0011100111100
output:- 4
uj5u.com熱心網友回復:
你很好,但你錯過了一件事:如果字符是'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;
}
uj5u.com熱心網友回復:
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;
}
uj5u.com熱心網友回復:
輸入字串可能被不是 的字符分割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'的字符,只計算給定字符的子序列。
uj5u.com熱心網友回復:
作為使用 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 回圈 - 但如果您經常執行它,這很重要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367356.html
上一篇:如何使用SQLite3資料庫更好地格式化 1000個條目的Django過濾器查詢?(運算式樹太大(最大深度1000))
下一篇:將計數查詢合二為一
