Skip to content

1839. Longest Substring Of All Vowels in Order 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int longestBeautifulSubstring(string word) {
    int ans = 0;
    int count = 1;

    for (int l = 0, r = 1; r < word.length(); ++r) {
      const char curr = word[r];
      const char prev = word[r - 1];
      if (curr >= prev) {
        if (curr > prev)
          ++count;
        if (count == 5)
          ans = max(ans, r - l + 1);
      } else {
        count = 1;
        l = r;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int longestBeautifulSubstring(String word) {
    int ans = 0;
    int count = 1;

    for (int l = 0, r = 1; r < word.length(); ++r) {
      final char curr = word.charAt(r);
      final char prev = word.charAt(r - 1);
      if (curr >= prev) {
        if (curr > prev)
          ++count;
        if (count == 5)
          ans = Math.max(ans, r - l + 1);
      } else {
        count = 1;
        l = r;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def longestBeautifulSubstring(self, word: str) -> int:
    ans = 0
    count = 1

    l = 0
    for r in range(1, len(word)):
      curr = word[r]
      prev = word[r - 1]
      if curr >= prev:
        if curr > prev:
          count += 1
        if count == 5:
          ans = max(ans, r - l + 1)
      else:
        count = 1
        l = r

    return ans