1678. Goal Parser Interpretation (C/C++)

2022. 8. 4. 21:43STUDY/LeetCode

반응형

You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order.

Given the string command, return the Goal Parser's interpretation of command.

 

Example 1:

Input: command = "G()(al)"
Output: "Goal"
Explanation: The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal".

Example 2:

Input: command = "G()()()()(al)"
Output: "Gooooal"

Example 3:

Input: command = "(al)G(al)()()G"
Output: "alGalooG"

 

Constraints:

  • 1 <= command.length <= 100
  • command consists of "G", "()", and/or "(al)" in some order.

아쥬 쉬운 문제쥬? 

# In C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* interpret(char *command) {
    int i = 0;
    int cnt = 0;
    int len = strlen(command);
    char *tmp = calloc(len+1, sizeof(char));

    for ( i = 0; i < len;i++) {
        if(command[i]== 'G') tmp[cnt++] = 'G';
        else if(command[i] == '(' && command[i+1] == ')') {
            tmp[cnt++] = 'o';
            i++;
        } else if(command[i] == '(' && command[i+1] == 'a') {
            tmp[cnt++] = 'a';
            tmp[cnt++] = 'l';
            i += 2;
        }
    }
    tmp[cnt] = '\0';
    return tmp;
}

int main () {
    //char cmd[20] = "G()(al)";
    char cmd[20] = "G()()()()(al)";
    printf("%s \n", interpret(cmd));

    return 0;
}

 

# in C++

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    string interpret(string command) {
        //cout << command << '\n';      
        int len = command.size();
        int cnt = 0;
        string tmp;
        for(int i = 0; i < len; i++) {
            if( command[i] == 'G') tmp += 'G';
            else if(command[i] == '(' && command[i+1] == ')') tmp+= 'o', i+=1;
            else if(command[i] == '(' && command[i+1] == 'a') tmp+='a', tmp+='l', i+=2;
        }
        //cout << command << '\n';      
        return tmp;
    }
}; // Do not forget semicolon !! 


int main()
{
    Solution sol;
    //char str[20] = "G()(al)";
    string str = "G()(al)";

    cout << sol.interpret(str) << '\n';

    return 0;
}

진작 C++로도 할껄......

껄껄껄 

나는 껄무새다 ~ㅋㅋㅋ

 

728x90
반응형