Skip to content

2042. Check if Numbers Are Ascending in a Sentence 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  bool areNumbersAscending(string s) {
    int prev = 0;
    istringstream iss(s);

    for (string token; iss >> token;)
      if (isdigit(token[0])) {
        const int num = stoi(token);
        if (num <= prev)
          return false;
        prev = num;
      }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public boolean areNumbersAscending(String s) {
    int prev = 0;

    for (final String token : s.split(" "))
      if (Character.isDigit(token.charAt(0))) {
        final int num = Integer.parseInt(token);
        if (num <= prev)
          return false;
        prev = num;
      }

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def areNumbersAscending(self, s: str) -> bool:
    prev = 0

    for token in s.split():
      if token.isdigit():
        num = int(token)
        if num <= prev:
          return False
        prev = num

    return True
Back to top