Checking Groups ( 6 kyu )

문제

In English and programming, groups can be made using symbols such as () and {} that change meaning. However, these groups must be closed in the correct order to maintain correct syntax.

Your job in this kata will be to make a program that checks a string for correct grouping. For instance, the following groups are done correctly:

({})
[[]()]
[{()}]

The next are done incorrectly:

{(})
([]
[])

주어진 문자열이 괄호로 완벽하게 닫혀있는지 판별하는 문제

풀이

 function groupCheck(s){
   while ( s.indexOf('()') !== -1 || s.indexOf('{}') !== -1 || s.indexOf('[]') !== -1 ) {
     if ( s.indexOf('()') !== -1 ) {
       s = s.slice(0, s.indexOf('()')) + s.slice(s.indexOf('()')+2, s.length);
     } else if ( s.indexOf('{}') !== -1 ) {
       s = s.slice(0, s.indexOf('{}')) + s.slice(s.indexOf('{}')+2, s.length);
     } else if ( s.indexOf('[]') !== -1 ) {
       s = s.slice(0, s.indexOf('[]')) + s.slice(s.indexOf('[]')+2, s.length);
     }
   }
   return (s === '')
 }

(), {}, [] 가 없을 때 까지 문자열에서 삭제해 빈 문자열이 남으면 true, 아니면 false 리턴

다른 사람의 풀이

 function groupCheck(s){
   var r = /\{\}|\[\]|\(\)/;
   while(r.test(s))
     s = s.replace(r, '');  
   return !s.length;   
 }

풀이는 비슷한데 정규식을 멋있게 쓴 것 같음


+ Recent posts