20-valid-parentheses-0807

몇월며칠·2022년 8월 7일

Leetcode

목록 보기
2/19
var isValid = function(s) {
	while (true) {
		if (s.indexOf('()') > -1) {
			s = s.replace('()', '')
		} else if (s.indexOf('[]') > -1) {
			s = s.replace('[]', '')
		} else if (s.indexOf('{}') > -1) {
			s = s.replace('{}', '')
		} else {
			return s === ''
		}
	}
};

JAVA 풀이였었지만 JS에도 .replace()가 있길래 그걸 활용한 답안을 찾고 싶었다.


.indexOf 정리

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

배열처럼 index도 0부터 시작한다.
그리고 주어진 값이 배열안에 포함되어 있지 않은 경우 -1을 반환한다.

즉, indexOf를 이용해서 짝이 맞는 괄호들은 전부 제거한 후에 남은 것이 없다면 true, 짝이 맞지 않아 남아있는 괄호가 있는 경우 false를 리턴한다.


while문 정리

조건문이 참일 때만 while문 속의 문장들이 실행된다.
반복문 속에 여러개의 문장을 사용하고 싶다면 중괄호 { } 를 통해 문장들을 하나로 묶어야 한다.

profile
What day is it today?

0개의 댓글