2019년 4월 13일 토요일

# 코딜리티-> Nesting 문제

코딜리티 레슨에 있는 문제이다. 일단 똑같이 레슨에 있는 Brackets 문제와 99.99% 동일한 문제라고 보면된다.

A string S consisting of N characters is called properly nested if:

  • S is empty;
  • S has the form "(U)" where U is a properly nested string;
  • S has the form "VW" where V and W are properly nested strings.

For example, string "(()(())())" is properly nested but string "())" isn't.

보시다시피 이전 Brackets 문제에서는 () {} []의 괄호가 등장했다면 여기서는 () 괄호만 등장한다. 풀이도 동일하다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
int Solution_Nesting(std::string &S) {
 std::stack<char> brackets;
 int strLen = S.length();
 for (int i = 0; i < strLen; i++) {
  if (brackets.size() > 0) {
   char lastInputChar = brackets.top();
   if ((lastInputChar == '(') && (S[i] == ')')) {
    brackets.pop();
   }
   else
    brackets.push(S[i]);
  }
  else
   brackets.push(S[i]);
 }

 if (brackets.size() > 0) return 0;
 else return 1;
}

댓글 없음:

댓글 쓰기