Home > Software engineering >  Leet Code 6181 Length of the Longest Alphabetical Continuous Substring
Leet Code 6181 Length of the Longest Alphabetical Continuous Substring

Time:09-19

class Solution {
public int longestContinuousSubstring(String s) {
    int count=0;
    for(int i=0;i<s.length();i  ){
            char ch = s.charAt(i);
            int castascii = (int) ch;
            int alpha=97;
        if(castascii==alpha){
            count  ;
        }
        alpha  ;
        }
       return count;
    }    
}

Example 1:

Input: s = "abacaba" // Only lower case

Output: 2

Explanation: There are 4 distinct continuous substrings: "a", "b", "c" and "ab". "ab" is the longest continuous substring.

Example 2:

Input: s = "abcde" // Only lower case

Output: 5

Explanation: "abcde" is the longest continuous substring.

My Code only Prints 1 Why is that?

I have used ASCII Values to solve can anyone help me.

CodePudding user response:

you're code is effectively counting how often the letter 'a' appears in a string.

class Solution {
public int longestContinuousSubstring(String s) {
    int count=0;
    for(int i=0;i<s.length();i  ){    // for each character in string
            char ch = s.charAt(i);
            int castascii = (int) ch;
            int alpha=97;             // you always set alpha to be 'a'
        if(castascii==alpha){         // checks if current char is an 'a'
            count  ;                  // effectively counting 'a's here
        }
        alpha  ;                     // this is redundant, u reset it in next iteration
        }
       return count;
    }    
}
  • Related