A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.
For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" are numbers and the other tokens such as "puppy" are words.
Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s).
Input: s ="1 box has 3 blue 4 red 6 green and 12 yellow marbles"Output: trueExplanation: The numbers in s are:1,3,4,6,12.They are strictly increasing from left to right:1<3<4<6<12.
Input: s ="sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s"Output: falseExplanation: The numbers in s are:7, _**51**_ , _**50**_ ,60. They are not strictly increasing.
We need to extract all numbers from the sentence and check if they are strictly increasing. This can be done efficiently by scanning the sentence token by token and comparing each number to the previous one.
By iterating through each token, we can identify numbers and compare each to the last seen number. If any number is not greater than the previous, the sequence is not strictly increasing.
classSolution {
publicbooleanareNumbersAscending(String s) {
int prev =-1;
for (String token : s.split(" ")) {
if (token.chars().allMatch(Character::isDigit)) {
int num = Integer.parseInt(token);
if (num <= prev) returnfalse;
prev = num;
}
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funareNumbersAscending(s: String): Boolean {
var prev = -1for (token in s.split(" ")) {
if (token.all { it.isDigit() }) {
val num = token.toInt()
if (num <= prev) returnfalse prev = num
}
}
returntrue }
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defare_numbers_ascending(self, s: str) -> bool:
prev =-1for token in s.split():
if token.isdigit():
num = int(token)
if num <= prev:
returnFalse prev = num
returnTrue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnare_numbers_ascending(s: String) -> bool {
letmut prev =-1;
for token in s.split_whitespace() {
iflet Ok(num) = token.parse::<i32>() {
if num <= prev {
returnfalse;
}
prev = num;
}
}
true }
}