본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1374. Generate a String With Characters That Have Odd Counts

반응형

https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/description/

 

Generate a String With Characters That Have Odd Counts - LeetCode

Can you solve this real interview question? Generate a String With Characters That Have Odd Counts - Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. The returned string must con

leetcode.com

규칙을 찾아 해결한 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

정답 변수 ans를 선언해줍니다.

📔 풀이과정

두 경우로 나뉩니다.

1. n이 짝수인 경우 : 홀수개의 a와 b한개로 유효 문자열을 만들 수 있습니다. n-1만큼 a를 ans뒤에 붙여준 뒤 b를 마지막에 한 개 붙여줍니다.

2. n이 홀수인 경우 : 홀수개의 a로 유효 문자열을 만들 수 있습니다. n만큼 a를 ans뒤에 붙여줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    string generateTheString(int n) {
        // 1 a
        // 2 a b
        // 3 a a a
        // 4 a a a b
        // 5 a a a a a
        string ans;
        if (n % 2) {
            for(int i = 0; i < n; i++) {
                ans += 'a';
            }
        } else {
            for(int i = 0; i < n - 1; i++) {
                ans += 'a';
            }
            ans += 'b';
        }
        return ans;
    }
};

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