2015年2月2日月曜日

Lesson 5 : Nesting (Nesting)

Lesson 5 : Nesting
https://codility.com/programmers/lessons/5

This question requires the space complexity of O(1).

The trick to achieve this is just to count the number of '(' and ')'. To add more, the number of ')' can not exceed the number of '(' otherwise the string is invalid. The string can also be empty.

This solution gives the 100% score.









int solution(char *S) 
{
    int lnum = 0;
    int rnum = 0;
    
    char *p = S;
    
    //the string can be empty. no need to scan.
    if (*p == NULL){
        return 1;
    }
    
    while(*p != NULL){
        if (*p == '('){
            lnum++;
        }
        else {
            //the number of ')' can never exceed the number of '('
            rnum++;
            if (rnum > lnum){
                return 0;
            }
        }
        p++;
    }
    
    return lnum == rnum;
}

0 件のコメント:

コメントを投稿