diff --git a/String/Count And Say b/String/Count And Say new file mode 100644 index 0000000..195372f --- /dev/null +++ b/String/Count And Say @@ -0,0 +1,47 @@ +/* +The count-and-say sequence is the sequence of integers beginning as follows: + +1, 11, 21, 1211, 111221, ... +1 is read off as one 1 or 11. +11 is read off as two 1s or 21. + +21 is read off as one 2, then one 1 or 1211. + +Given an integer n, generate the nth sequence. + +Note: The sequence of integers will be represented as a string. + +Example: + +if n = 2, +the sequence is 11. +*/ + + +string Solution::countAndSay(int n) { + if (n == 1) return "1"; + if (n == 2) return "11"; + string str = "11"; + for (int i = 3; i<=n; i++) + { + str += '$'; + int len = str.length(); + + int cnt = 1; + string tmp = ""; + + for (int j = 1; j < len; j++) + { + + if (str[j] != str[j-1]) + { + tmp += cnt + '0'; + tmp += str[j-1]; + cnt = 1; + } + else cnt++; + } + str = tmp; + } + return str; +}