Given a string s = \'011110010000000100010111\', the length of the longest subst
ID: 3693159 • Letter: G
Question
Given a string s = '011110010000000100010111', the length of the longest substring of s which contains consecutive ‘1's would be 4. Write a function named longest_one , which accepts one input string consisting only of ‘0’ and ‘1’ characters. The function should return the size of the longest substring of consecutive ‘1’s. You are required to use the programming method (loops, conditional statements). The function should return the desired output regardless of the input string size . Here's an example of a function call:
Explanation / Answer
LongOnes.java
public class LongOnes {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "011110010000000100010111";
int longOneCount = longest_one(s);
System.out.println("The Max 1's of Given string is : "+longOneCount);
}
public static int longest_one(String s){
int maxCount = 0;
int> for(int i=0; i<s.length()-1; i++){
if(s.charAt(i) == '1' && (s.charAt(i) == s.charAt(i+1))){
oneCount++;
if(i+1 == s.length()-1){
if(maxCount < oneCount){
maxCount =oneCount;
}
}
}
else{
if(maxCount < oneCount){
maxCount =oneCount;
}
> }
}
return maxCount;
}
}
Output:
The Max 1's of Given string is : 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.