Created
April 18, 2025 18:13
-
-
Save SuryaPratapK/179f203053af28da44d7dc5eb6109704 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string countAndSay(int n) { | |
if(n==1) return "1"; | |
string number = "1"; | |
for(int i=2;i<=n;++i){ | |
//Build new string | |
string res; | |
int count = 1; | |
char curr = number[0]; | |
for(int j=1;j<number.size();++j){ | |
if(number[j]==curr) count++; | |
else{ | |
res += to_string(count) + curr; | |
curr = number[j]; | |
count = 1; | |
} | |
} | |
res += to_string(count) + curr; | |
number = res; | |
} | |
return number; | |
} | |
}; | |
/* | |
//JAVA | |
class Solution { | |
public String countAndSay(int n) { | |
if (n == 1) return "1"; | |
StringBuilder number = new StringBuilder("1"); | |
for (int i = 2; i <= n; i++) { | |
StringBuilder res = new StringBuilder(); | |
int count = 1; | |
char curr = number.charAt(0); | |
for (int j = 1; j < number.length(); j++) { | |
if (number.charAt(j) == curr) { | |
count++; | |
} else { | |
res.append(count).append(curr); | |
curr = number.charAt(j); | |
count = 1; | |
} | |
} | |
res.append(count).append(curr); | |
number = res; | |
} | |
return number.toString(); | |
} | |
} | |
#Python | |
class Solution: | |
def countAndSay(self, n: int) -> str: | |
if n == 1: | |
return "1" | |
number = "1" | |
for _ in range(2, n + 1): | |
res = [] | |
count = 1 | |
curr = number[0] | |
for j in range(1, len(number)): | |
if number[j] == curr: | |
count += 1 | |
else: | |
res.append(str(count) + curr) | |
curr = number[j] | |
count = 1 | |
res.append(str(count) + curr) | |
number = "".join(res) | |
return number | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment