Skip to content

Commit

Permalink
remove 38 Count and Say
Browse files Browse the repository at this point in the history
  • Loading branch information
selfboot committed Jul 14, 2016
1 parent dcd09db commit 996a283
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 12 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
* 014. [Longest Common Prefix](String/14_LongestCommonPrefix.py)
* 017. [Letter Combinations of a Phone Number](String/17_LetterCombinationsPN.py)
* 028. [Implement strStr()](String/28_ImplementstrStr.py)
* 038. [Count and Say](String/38_CountAndSay.py)
* 058. [Length of Last Word](String/58_LengthOfLastWord.py)
* 067. [Add Binary](String/67_AddBinary.py)
* 068. Text Justification
Expand Down
35 changes: 35 additions & 0 deletions String/38_CountAndSay.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* @Author: [email protected]
* @Last Modified time: 2016-07-14 19:12:37
*/

class Solution {
public:
string countAndSay(int n) {
int index = 2;
string pre_str = "1";
while(index <= n){
string new_str = "";
int i=0;
while(i < pre_str.size()){
int count = 1;
char c = pre_str[i];
i += 1;
while(i < pre_str.size() && pre_str[i]==c){
count++;
i++;
}
new_str += to_string(count) + c;
}
pre_str = new_str;
index ++;
}
return pre_str;
}
};

/*
1
5
15
*/
28 changes: 16 additions & 12 deletions Week05/38.py → String/38_CountAndSay.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@


class Solution(object):
""" Quite straight-forward solution.
We generate k-th string, and from k-th string we generate k+1-th string,
until we generate n-th string.
"""
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n <= 1:
return "1"

Expand All @@ -16,23 +17,26 @@ def countAndSay(self, n):
# Get the ith count-and-say sequence by scan pre_str
length = len(pre_str)
current_str = ""
index = 0

# Count and say the pre_str
index = 0
while index < length:
char = pre_str[index]
repeat = 0
pos = repeat + index + 1
pos = index + 1
while pos < length and pre_str[pos] == char:
repeat += 1
pos = repeat + index + 1
pos += 1

if repeat:
current_str = current_str + str(repeat + 1) + char
else:
current_str = current_str + "1" + char
index = index + repeat + 1
current_str += str(repeat + 1) + char
index = pos

pre_str = current_str

return pre_str

"""
1
5
15
"""

0 comments on commit 996a283

Please sign in to comment.