Leetcode 2042. Check if Numbers Are Ascending in a Sentence
You are given a string s
representing a sentence containing words and numbers. Your task is to determine if the numbers in the sentence are strictly ascending.
A sentence is a list of tokens separated by a single space. Tokens can be either words or numbers. A word consists of only lowercase English letters, while a number consists of only digits.
Return true
if the numbers in s
are strictly ascending, otherwise return false
.
s
will only contain lowercase English letters, digits, and spaces.true
if all numbers in the sentence are in strictly ascending order.false
otherwise.s
by spaces to isolate individual tokens.#include <string>
#include <sstream>
#include <climits>
#include <iostream>
bool areNumbersAscending(std::string s) {
std::istringstream stream(s);
std::string token;
int prevNumber = INT_MIN;
while (stream >> token) {
// Check if the token is a number
bool isNumber = true;
for (char c : token) {
if (!isdigit(c)) {
isNumber = false;
break;
}
}
if (isNumber) {
int number = std::stoi(token);
if (number <= prevNumber) {
return false;
}
prevNumber = number;
}
}
return true;
}
// Sample Usage
int main() {
std::string s1 = "1 box has 3 blue 4 red 7 green and 8 yellow marbles";
std::string s2 = "5 hello 2 world";
std::string s3 = "this is a test 1 2 3";
std::cout << std::boolalpha << areNumbersAscending(s1) << std::endl; // True
std::cout << std::boolalpha << areNumbersAscending(s2) << std::endl; // False
std::cout << std::boolalpha << areNumbersAscending(s3) << std::endl; // True
return 0;
}
In total, the time complexity is O(n), which is efficient for the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?