JavaScript - LeetCode Random Algorithm Test(4)

먹보·2023년 3월 4일
0

1. Valid Parentheses (No.0020)

문제 설명

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

해석

소,중,대괄호로만 구성되어 있는 문자열이 주어졌을 때, 검증된 문자열인지 확인하는 함수를 구현해주세요.

검증된 문자열이란..

  1. 한 번 괄호가 열리면 반드시 열린 괄호와 같은 종류로 닫혀야 합니다.

  2. 올바른 순서대로 괄호가 닫혀야 합니다.

  3. 괄호는 항상 짝을 이뤄야 합니다.

예제

그리고 추가적으로..저 예제만으로는 파악하기 어려운 것이 하나 있어서 추가 테스트 케이스도 작성해본다.

s = "([)]"
return false

s = "{[]}"
return true

코드

var isValid = function(s) {
    
    const pairs = {
    "(": ")",
    "[": "]",
    "{": "}"
    }
 
    if (s.length % 2 === 1) return false

    if (Object.values(pairs).includes(s[0])) return false
    
    if (pairs.hasOwnProperty(s[s.length-1])) return false
    
    
    let stack = []
    
    for(let i=0; i<s.length; i++) {
        if(pairs.hasOwnProperty(s[i])) {
            stack.push(s[i])
        } else if (pairs[stack.pop()] !== s[i]) {
            return false
        }
        
    }
    return stack.length === 0
    
};

🗒️코멘트

우선 Early Return 패턴을 이용하여 문자열의 길이가 짝수 (괄호가 쌍을 이루지 못했다는 것)가 아닌 경우, 문자열의 시작이 닫힌 괄호의 경우, 그리고 끝이 열린 괄호의 경우의 수를 모드 제하였고 for 문을 돌면서 stack이라는 배열 내부에서 처리 할 수 있겠금 설정하였습니다.


2. Keep Multiplying Found Values by Two (No.2154)

문제 설명

You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums.
You then do the following steps:

  1. If original is found in nums, multiply it by two (i.e., set original = 2 * original).
  2. Otherwise, stop the process.
  3. Repeat this process with the new number as long as you keep finding the number.

Return the final value of original.

해석

정수가 담긴 배열 nums와 하나의 정수 original이 주어졌을 때, 다음과 같은 프로세스를 반복하세요.

  1. 만약 original이 nums의 배열 안에 있을 경우 original을 2배 하세요.

  2. 만약 없다면 바로 프로세스를 끝내시면 됩니다.

  3. 1번을 2번을 만족할 때 까지 반복하세요.

프로세스가 끝났을 때 바뀐 original을 반환해 주세요.

예제

코드

var findFinalValue = function(nums, original) {
    while(nums.includes(original)){
        original *= 2
    }
    return original
};

🗒️코멘트


3. Maximum Count of Positive Integer and Negative Integer (No.2529)

문제 설명

Given an array nums sorted in non-decreasing order, return the maximum between the number of positive integers and the number of negative integers.
In other words, if the number of positive integers in nums is pos and the number of negative integers is neg, then return the maximum of pos and neg.

해석

숫자가 담긴 배열이 오름차순으로 주어졌을 때, 양수의 숫자와 음수의 숫자 중 더 큰 수를 반환하는 함수를 구현해주세요.

예제

코드

var maximumCount = function(nums) {
    let pos = 0;
    let neg = 0;
    for (let i = 0 ; i < nums.length ; i++){
        if (nums[i] > 0){
            pos++
        } else if (nums[i] < 0){
            neg++
        }
    }
    return Math.max(pos,neg)
};

🗒️코멘트

profile
🍖먹은 만큼 성장하는 개발자👩‍💻

0개의 댓글