본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1370. Increasing Decreasing String

반응형

https://leetcode.com/problems/increasing-decreasing-string/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

구현문제였습니다.

 

📕 풀이방법

📔 입력 및 초기화

정답 변수 res, alphabat별 빈도수 freq를 선언 후 값을 구해 저장 해줍니다.

📔 풀이과정

res가 s길이보다 적은 동안 while loop를 수행합니다.

1. 오름차순으로 각 alphabat별 loop를 수행하며 freq가 1이상인 문자를 골라 res에 추가해줍니다.

2. 내림차순으로 각 alphabat별 loop를 수행하며 freq가 1이상인 문자를 골라 res에 추가해줍니다.

📔 정답 출력 | 반환

res를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    string sortString(string s) {
        string res = "";
        int freq[26] = {0};

        for(auto c : s) {
            freq[c - 'a']++;
        }
        
        while(s.size() > res.size()) {
            for(int i = 0; i < 26; i++) {
                if(freq[i]) {
                    res += i + 'a';
                    freq[i]--;
                }
            }

            for(int i = 25; i >= 0; i--) {
                if(freq[i]) {
                    res += i + 'a';
                    freq[i]--;
                }
            }
        }
        
        return res;
    }
};

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