[C++] 리트코드 Count and Say

2024. 2. 26. 00:57·Algorithm/HackerRank, LeetCode
class Solution 
{
public:
    string countAndSay(int n) 
    {
        if (n == 1)
        {
            return "1";
        }

        string result = countAndSay(n - 1);
        
        //left Count right Num 
        string currResult;
        char currNum = result[0];
        int currCount = 0;

        for (int j = 0; j < result.length(); j++) 
        {
            if (currNum == result[j]) 
            {
                currCount++;
            }
            if (currNum != result[j]) 
            {
                currResult += to_string(currCount) + currNum;

                currCount = 1;
                currNum = result[j];
            }
        }

        currResult += to_string(currCount) + currNum;
        result = currResult;

        return result;
    }
};

 

풀이

1. 다른 숫자가 나올 때마다 개수를 세서 왼쪽에는 개수 오른쪽은 해당 숫자를 적립해준다.

2. 그것을 n번 만큼 반복해준다.

 

 

느낀점

반복할 때 값을 어떻게 넣을 것인지에 대해 빠르게 생각해야될 것같다.

 

 

 

https://leetcode.com/problems/count-and-say/

 

Count and Say - LeetCode

Can you solve this real interview question? Count and Say - The count-and-say sequence is a sequence of digit strings defined by the recursive formula: * countAndSay(1) = "1" * countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1

leetcode.com

 

저작자표시 (새창열림)

'Algorithm > HackerRank, LeetCode' 카테고리의 다른 글

[C++] 리트코드 221. Maximal Square  (1) 2024.02.16
[C++] 리트코드 279. Perfect Squares  (0) 2024.02.16
[C++] 해커랭크 Cut the Tree  (0) 2023.12.26
'Algorithm/HackerRank, LeetCode' 카테고리의 다른 글
  • [C++] 리트코드 221. Maximal Square
  • [C++] 리트코드 279. Perfect Squares
  • [C++] 해커랭크 Cut the Tree
chanheess
chanheess
'왜' 그렇게 했는가?에 대한 생각으로 공부 및 작업의 저장관리
  • chanheess
    왜 그렇게 생각했는가?
    chanheess
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Backend Programming
      • Game Programming
        • Unreal
        • DirectX
      • C++
        • Memo
        • Basic
        • Effective Modern
      • Java
      • Algorithm
        • Memo
        • Baekjoon
        • Programmers
        • HackerRank, LeetCode
      • Data Structure
      • Design Pattern
      • Etc
        • Memo
        • Daily Log
        • Book
  • 최근 글

  • 최근 댓글

  • 태그

    백준
    JWT
    프로그래머스
    SpringSecurity
    티스토리챌린지
    dfs
    JPA
    dp
    위클리 챌린지
    Java
    c++ 기초 플러스
    알고리즘
    오블완
    spring
  • hELLO· Designed By정상우.v4.10.0
chanheess
[C++] 리트코드 Count and Say

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.