[LeetCode] Check if Numbers Are Ascending in a Sentence

준규·2023년 3월 14일
0

1.문제


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.


공백 하나로 구분되어있는 숫자와 단어가 섞인 문자열이 주어질 때 문자열 내 숫자들이 왼쪽부터 오른쪽으로 보았을때 오름차순이면 true , 아니라면 false를 리턴하는 문제이다.


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

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.

2.풀이

  1. 문자열에서 숫자를 뽑아낸다.
  2. 숫자만 있는 배열을 정렬한다.
  3. 원본 배열과 정렬된 배열을 비교한다.

/**
 * @param {string} s
 * @return {boolean}
 */
const areNumbersAscending = function (s) {
  const tokens = s.split(" ");
  const numTokens = [];
  // token중에서 숫자 token을 추출한다.
  tokens.forEach((token) => {
    const temp = parseInt(token);
    if (!isNaN(temp)) numTokens.push(temp);
  });

  // 정렬할 숫자 token 배열을 할당한다.
  const sorted = [...numTokens];

  // 오름차순으로 정렬
  sorted.sort((a, b) => a - b);

  // 원본 배열과 정렬된 배열을 비교해서 서로 다르거나 현재 숫자와 이전 숫자가 같은 값이면 false를 리턴한다.
  for (let i = 0; i < numTokens.length; i++) {
    if (numTokens[i] !== sorted[i] || numTokens[i] === numTokens[i - 1]) {
      return false;
    }
  }

  // for문을 무사히 다 돌면 true를 리턴한다.
  return true;
};

3.결과

profile
안녕하세요 :)

0개의 댓글