본문 바로가기
코딩테스트/Codility

[C++ 풀이] Codility - Lessons 7, (Stacks and Queues) Nesting

by Hwan2 2019. 9. 29.
728x90
반응형

 

 

 

 

이 문제는 Codility 사이트에서 확인하고 문제를 풀 수 있습니다.

https://www.codility.com/

 

 

 

문제

 

 

 

 

 

 

설명

 

 

배열 S에 대해 '('와 ')'이 대칭을 이루면 1반환, 아니면 0반환.

배열 S가 아무것도 없어도 1반환.

 

 

배열의 길이는 0 ~ 1,000,000

배열 S의 요소는 무조건 '(' or ')'

 

 

 

 

 

 

 

결과

 

// you can use includes, for example:
// #include <algorithm>
#include <stack>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int solution(string &S) {
    // write your code in C++14 (g++ 6.2.0)
    stack<char> s;
    int count = 0;
    
    if(S.empty())
        return 1;
    
    
    if(S.size() % 2 == 1 || S[0] != '(')
        return 0;
        
        
    for(int i = 0; i < S.size(); i++){
        if(s.empty() && S[i] == ')')
            return 0;
        
        if(S[i] == '(')
            s.push(S[i]);
        else{
            s.pop();
            count++;
        }
            
    }
    
    if(s.empty() && count == S.size() / 2)
        return 1;
    else
        return 0;   
}
 

 

 

https://app.codility.com/demo/results/trainingEVZAVD-2B6/

 

 

 

 

 

다른풀이

 

// you can use includes, for example:
// #include <algorithm>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int solution(string &S) {
    // write your code in C++14 (g++ 6.2.0)

    int count = 0;
    
    for(int i = 0; i < S.size(); i++){
        if(S[i] == '(')
            count++;
        else if(S[i] == ')')
            count--;
            
        if(count < 0)
            return 0;
    }
    
    return count == 0 ? 1 : 0;
}
 

 

 

https://app.codility.com/demo/results/trainingXPB7AV-Y3F/

 

 

 

 

코딩테스트를 본 후 다른분들은 어떻게 풀었는지도 보는게 도움이 많이 되는것 같네요!!

반응형

댓글


스킨편집 -> html 편집에서