From f49a4b94bf127007f3afbea715196c8327eca0f9 Mon Sep 17 00:00:00 2001 From: Pranita <34750485+PranitaJindal@users.noreply.github.com> Date: Sat, 29 Jun 2019 18:34:06 +0530 Subject: [PATCH] Create Count And Say --- String/Count And Say | 47 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 String/Count And Say 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; +}