넘치게 채우기

[LeetCode] 2785. Sort Vowels in a String 본문

PS/LeetCode

[LeetCode] 2785. Sort Vowels in a String

riveroverflow 2023. 11. 13. 11:02
728x90
반응형

https://leetcode.com/problems/sort-vowels-in-a-string/description/

 

Sort Vowels in a String - LeetCode

Can you solve this real interview question? Sort Vowels in a String - Given a 0-indexed string s, permute s to get a new string t such that: * All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such

leetcode.com

leetcode - Sort Vowels in a String

문제 유형 : 문자열 처리 / 정렬

문제 난이도 : Medium

 

문제

Given a 0-indexed string s, permute s to get a new string t such that:

  • All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i].
  • The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j].

Return the resulting string.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.

 

문자열 s가 주어진다. 아래 조건에 맞게 s를 재배열하라.

- 모든 자음은 그대로 있는다.

- 모음은 모음끼리 아스키코드의 값에 근거하여 비내림차순으로 정렬되어야 한다.

 

정렬 후 결과를 반환하라.

모음은 'a', 'e', 'i', 'o', 'u'이고, 대문자로도, 소문자로도 나올 수 있다.

자음은 모음이 아닌 모든 철자가 나올 수 있다.

 

풀이

문자열을 한 번 순회하면서 모음과 모음의 인덱스만 따로 담는다.

모음들을 정렬하고, 모음이 있던 인덱스에 새로 대입해주면 된다.

정렬은 따로 비교식을 사용할 필요 없이, 그냥 정렬하면 아스키코드순으로 비내림차순 정렬이 된다.

 

 

코드

C++

class Solution {
public:
    string sortVowels(string s) {
        ios_base::sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);

        vector<char> str;
        vector<int> vowelIdx;
        vector<char> vowels;
        unordered_map<char, int> isVowel = {
            {'a', 1},
            {'e', 1},
            {'i', 1},
            {'o', 1},
            {'u', 1},
            {'A', 1},
            {'E', 1},
            {'I', 1},
            {'O', 1},
            {'U', 1}
        };

        for(int i = 0; i < s.size(); i++) {
            char ch = s[i];
            if(isVowel[ch] == 1) {
                vowels.push_back(ch);
                vowelIdx.push_back(i);
            } 
            str.push_back(ch);
        }

        sort(vowels.begin(), vowels.end());

        for(int i = 0; i < vowels.size(); i++) {
            str[vowelIdx[i]] = vowels[i];
        }

        string sorted = "";
        for(const auto &ch : str) {
            sorted += ch;
        }

        return sorted;
    }
};
 
728x90
반응형