carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2042: Check if Numbers Are Ascending in a Sentence #328

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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).

Return true if so, or false otherwise.

Example 1:

image

example-1 Input: s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles" Output: true Explanation: The numbers in s are: 1, 3, 4, 6, 12. They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.

Example 2:

Input: s = "hello world 5 x 5" Output: false Explanation: The numbers in s are: 5, 5. They are not strictly increasing.

Example 3:

image

example-3 Input: s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s" Output: false Explanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing.

Constraints:

3 <= s.length <= 200 s consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive. The number of tokens in s is between 2 and 100, inclusive. The tokens in s are separated by a single space. There are at least two numbers in s. Each number in s is a positive number less than 100, with no leading zeros. s contains no leading or trailing spaces.

carloscn commented 1 year ago

Analysis

int32_t are_number_ascending(const char *s, bool *result)
{
    int32_t ret = 0;
    size_t i = 0;
    size_t len = 0;
    int32_t last_num = -1;

    UTILS_CHECK_PTR(s);
    UTILS_CHECK_PTR(result);
    UTILS_CHECK_LEN(len = strlen(s));

    while (i < len) {
        if (isdigit(s[i])) {
            char temp[16] = {0};
            int32_t current_num = 0;
            size_t j = 0;
            while (s[i] != ' ' && i < len) {
                temp[j ++] = s[i ++];
            }
            temp[j] = '\0';
            current_num = atoi(temp);
            if (last_num < current_num) {
                last_num = current_num;
                continue;
            }
            *result = false;
            goto finish;
        }
        i ++;
    }

    *result = true;

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168494 https://github.com/carloscn/structstudy/commit/cbdc7cc0a164b7e3099d495ede463ae111fdc021