문제 URL : https://leetcode.com/problems/count-and-say/submissions/
Count and Say - LeetCode
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
문제접근법 :
문제가 이해하기 어려웠습니다. 이해하기만하면 쉬운데 무슨말인지
이해하려고 찾아보다 이해하고 코드로 짜는건 어렵지 않은 문제입니다.
n=1일때 무조건 1입니다. 이건 이해할것없이 문제자체에서 정해줍니다.
n=2 부터 n까지는 이전의 숫자가 어떻게 진행되는지 카운트하면서 보여줍니다
아래 그림과같이
처음 숫자가 몇인지 확인한우 연속된수가 몇개인지 카운트하면서 숫자를 만들어나가면 되는 원리이기때문에
문제 설명이 애매하지만 이해하면 바로 코드로 쉽게 코딩할수 있는 문제입니다.
소스코드 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
//By 콩순이냉장고
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string countAndSay(int n) {
string ans = "1";
for (int num = 2; num <= n; num++) {
int add = 1;//연속된 숫자의 개수
string s="";
for (int i = 0; i < ans.size(); i+=add) {//해당자리에서 연속된것이 몇개인지
int cnt = 1;
for (int j = i + 1; j < ans.size(); j++,cnt++) {
if (ans[i] != ans[j])break;
}
s += to_string(cnt) + ans[i];
add = cnt;
}
ans = s;
}
return ans;
}
};
|
cs |
궁금한점 혹은 모르는점 혹은 논리적인 오류등 질문은 언제나 환영입니다.
'LeetCode' 카테고리의 다른 글
LeetCode 572. Subtree of Another Tree (0) | 2021.07.31 |
---|---|
LeetCode 459 Repeated Substring Pattern (0) | 2021.07.31 |
LeetCode ZigZag Conversion (0) | 2021.07.14 |
LeetCode 28 Implement strStr() (0) | 2021.07.06 |
LeetCode 59 Spiral Matrix II (0) | 2021.02.10 |