본문 바로가기

Algorithm/String

(C++) - LeetCode (easy) 824. Goat Latin

반응형

https://leetcode.com/problems/goat-latin/description/

 

Goat Latin - LeetCode

Can you solve this real interview question? Goat Latin - You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin" (a made-up

leetcode.com

문자열 다루는 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 공백 문자 ' '를 구분자로해 split함수를 구현합니다. stringstream을 사용하면 쉽게 split된 vector string값들을 얻을 수 있습니다.2. split함수의 반환값을 vector words를 선언해 저장합니다.3. 정답을 변환할 변수 ans를 선언합니다.

📔 풀이과정

조건 그대로 구현하면 됩니다. words의 원소를 순회하며 다음을 수행합니다.

1. 단어 첫 글자가 모음이라면 단어 끝에 "ma"만 붙여줍니다.

2. 아니라면 첫 글자를 단어 끝으로 옮기고 "ma"를 붙여줍니다.

3. index + 1만큼 'a'를 붙여줍니다.

📔 정답 출력 | 반환

1. 바꾼 words를 순회하며 string으로 변환해 ans에 ' '를 더하고 붙여줍니다. 매번 공백을 넣어줘야하므로 마지막에 공백이 포함됩니다. 따라서 loop끝난 후 pop_back해줌에 주의합니다.

2. ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector <string> split(string input, char delimeter) {
        vector <string> res;
        stringstream ss(input);
        string tmp;
        while(getline(ss,tmp,delimeter)) {
            res.push_back(tmp);
        }
        return res;
    }
    bool isVowel(char c){
        return c == 'a' || c == 'e' || c == 'i' || c =='o' || c=='u';
    }

    string toGoatLatin(string sentence) {
        vector <string> words = split(sentence, ' ');
        string ans;
        for(int i = 0; i < words.size(); i++) {
            string &word = words[i];
            if(isVowel(tolower(word[0]))) {
                word += "ma";
            } else {
                word = word.substr(1) + word[0] + "ma";
            }
            string a(i+1,'a'); 
            word += a;
        }
        for(auto w : words) {
            ans += w + " ";
        }
        ans.pop_back();
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.