leetcode
  • Coding Interview Prep
  • Data structure
    • String
    • List
    • Matrix
    • Dictionary
    • Tuple
    • Set
    • Tree
    • Stack
  • Array
    • 1_Two Sum
    • 15_Three Sum
    • 21_Merge Two Sorted Lists
    • 26_Remove Duplicates from Sorted Array
    • 27_Remove Element
    • 31_Next Permutation
    • 56_Merge Intervals
    • 57_Insert Interval
    • 66_Plus One
    • 80_Remove Duplicates from Sorted Array II
    • 81_Search in Rotated Sorted Array II
    • 88_Merge Sorted Array
    • 121_Best Time to Buy and Sell Stock
    • 122_Best Time to Buy and Sell Stock II
    • 123_Best Time to Buy and Sell Stock III
    • 167_Two Sum II - Input array is sorted
    • 169_Majority Element
    • 170_Two Sum III - Data Structure Design
    • 189_Rotate Array
    • 238_Product of Array Except Self
    • 243_Shortest Word Distance
    • 244_Shortest Word Distance II
    • 245_Shortest Word Distance III
    • 252_Meeting Rooms
    • 277_Find the Celebrity
    • 283_Move Zeroes
    • 349_Intersection of Two Arrays
    • 350_Intersection of Two Arrays II
    • 605_Can Place Flowers
    • 653_Two Sum IV - Input is a BST
    • 674_Longest Continuous Increasing Subsequence
    • 714_Best Time to Buy and Sell Stock with Transaction Fee
    • 724_Find Pivot Index
    • 747_Largest Number At Least Twice of Others
    • Sort an Array in Wave Form
    • Permute Elements of An Array
    • Reservoir Sampling (online)
    • Reservoir Sampling (offline)
  • Matrix
    • 36_Valid Sudoku
    • 48_Rotate Image
    • 54_Spiral Matrix
    • 59_Spiral Matrix II
    • 118_Pascal's Triangle
    • 119_Pascal's Triangle II
    • 240_Search a 2D Matrix II
    • 311_Sparse Matrix Multiplication
    • 498_Diagonal Traverse
  • String
    • 5_Longest Palindromic Substring
    • 6_ZigZag Conversion
    • 14_Longest Common Prefix
    • 17_Letter Combinations of a Phone number
    • 20_Valid Parentheses
    • 28_Implement strStr()
    • 38_Count and Say
    • 43_Multiply Strings
    • 49_Group Anagrams
    • 93_Restore IP Address
    • 125_Valid Palindrome
    • 151_Reverse Words in a String
    • 157_Read N Characters Given Read4
    • 242_Valid Anagram
    • 266_Palindrome Permutation
    • 344_Reverse String
    • 387_First Unique Character in a String
    • 647_Palindromic Substrings
    • 678_Valid Parenthesis String
    • 680_Valid Palindrome II
    • 709_To Lower Case
    • 819_Most Common Word
    • 833_Find and Replace in String
  • Search
    • 33_Search in Rotated Sorted Array
    • 34_Find First and Last Position of Element in Sorted Array
    • 35_Search Insert Position
    • 153_Find Minimum in Rotated Sorted Array
    • 215_Kth Largest Element in an Array
    • 268_Missing Number
    • 278_First Bad Version
    • 339_Nested List Weight Sum
    • 364_Nested List Weight Sum II
  • Math
    • 12_Integer to Roman
    • 13_Roman to Integer
    • 29_Divide Two Integers
    • 67_Add Binary
    • 69_Sqrt(x)
    • 168_Excel Sheet Column Title
    • 171_Excel Sheet Column Number
    • 204_Count Primes
    • 504_Base 7
    • 628_Maximum Product of Three Numbers
    • Multiply Two Integers
    • Smallest Non-constructible Value
    • SORT5
  • DP
    • 53_Maximum Subarray
    • 152_Maximum Product Subarray
    • 256_Paint House
    • 300_ Longest Increasing Subsequence
    • 747_Min Cost Climbing Stairs
    • 377_Combination Sum IV
  • Hash Table
    • 535_Encode and Decode TinyURL
  • Tree
    • 94_Binary Tree Inorder Traversal
    • 102_Binary Tree Level Order Traversal
    • 103_Binary Tree Zigzag Level Order Traversal
    • 104_Maximum Depth of Binary Tree
    • 113_Path Sum II
    • 144_Binary Tree Preorder Traversal
    • 145_Binary Tree Postorder Traversal
    • 235_Lowest Common Ancestor of a Binary Search Tree
    • 236_Lowest Common Ancestor of a Binary Tree
    • 257_Binary Tree Paths
    • 404_Sum of Left Leaves
    • 543_Diameter of Binary Tree
    • 572_Subtree of Another Tree
    • 637_Average of Levels in Binary Tree
  • Linked List
    • 2_Add Two Numbers
    • 206_Reverse Linked List
    • 234_Palindrome Linked List
  • Recursion
    • Tower of Hanoi
  • Backtracking
    • 51_N-Queens
    • 52_N-Queens II
    • 46_ Permutations
    • 77_ Combinations
    • 78_Subsets
    • 22_Generate Parentheses
    • 131_ Palindrome Partitioning
  • Bit Manipulation
    • 461_Hamming Distance
  • Python
    • for ... else ...
    • dictionary.get( ) vs dictionary[ ]
    • Read and write data file
    • List Comprehension
    • Lambda
    • Receiving Tuples and Dictionaries as Function Parameters
    • The assert statement
    • Miscellaneous
    • Python shortcuts
  • template
  • facebook
Powered by GitBook
On this page
  • Solution: iterative
  • Note:

Was this helpful?

  1. String

38_Count and Say

[Easy]

The count-and-say sequence is the sequence of integers with the first five terms as following:

1
11
21
1211
111221

1is read off as"one 1"or11. 11is read off as"two 1s"or21. 21is read off as"one 2, thenone 1"or1211.

Given an integern, generate thenthterm of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1

Output: "1"

Example 2:

Input: 4

Output: "1211"

Solution: iterative

Idea:

  • The elements in the sequence are computed from the counting and saying for each number from previous element

  • For each string in the sequence, loop over the whole string, count the frequence and record the letter, add into the output sequentially

def countAndSay(n):
    """
    :type n: int
    :rtype: str
    """
    ret = '1'
    for i in range(1, n):
        ret_new = ''
        digit = ret[0]
        count = 0
        for cur in ret:
            if cur == digit:
                count += 1
            else:
                ret_new += str(count) + digit
                digit = cur
                count = 1    
        ret_new += str(count) + digit
        ret = ret_new
    return ret

Note:

Proof by exhaustion and contrapositive:

In order for a number greater than 4 to be created, there must be a series of numbers n>4 in length all the same digit. Therefore, there is a subset of that series where the count would only reach 4. Because of this, any proof for the existence of a chain resulting in a number greater than 4 is also a proof for the existence of a 4-chain. Using the proof by contrapositive, this means that if 4-chains are proved to be impossible, then any n-chain with n>4 is also impossible.

In order to start with a chain with numbers greater than 4, you must assume that a 4-chain is possible in the first place, which is circular reasoning, and so cannot be used as an initial point. It is further impossible to have a negative value, since the counting numbers do not include them.

Therefore, the only chains able to create a 4 (at least the first one) are 0000, 1111, 2222, or 3333.

0 0 0 0 -> 40 The 0000 is read zero 0, zero 0, which must come from . Since there is nothing present, it could in theory occur anywhere in the string. However, since they would be next to each other, if the 0 is repeated as would be neccessary, the zeros would add together, resulting in just zero 0, leaving only 20, not 40.

1 1 1 1 -> 41 The 1111 is read one 1, one 1 (or 11), which translates to 21, not 1111. This contradicts the assumption that there is a way to get 1111, and so prevents 4 or greater from appearing. Therefore, 1s cannot reach 4.

2 2 2 2 -> 42 The 2222 is read two 2, two 2 (or 22 22), which is identical to the output. Since the input maps to itself, there is no way to leave that cycle, or it already would have. If 2222 exists in the input, then 2222 must have mapped to it. It cannot reach 42. Therefore, 2s cannot reach 4.

3 3 3 3 -> 43 The 3333 is read three 3, three 3 (or 333 333). This in turn would require 333 333 333. This fails in two respects. First, that the previous inputs would not merge to 63 or 93. The second, that the sequence eventually traces back to the origin, 1. Since it keeps increasing in length as the number of rounds since the start decreases, it cannot have started at 1. Therefore, 3s cannot reach 4.

As every possible case has been examined, and none can reach a 4 while starting at the given beginning (1), it is not possible for a 4-chain to occur, meaning a 4 cannot appear in any valid string for this problem. Further, as stated above, since a 4-chain is impossible, so too are all n-chains with n>4, so no number greater than 4 can appear either.

Previous28_Implement strStr()Next43_Multiply Strings

Last updated 5 years ago

Was this helpful?

Time Complexity: O(2nn)O(2^n n)O(2nn) because the length of next string may be double of the length of previous string.

Space Complexity: O(2n)O(2^n)O(2n) for the output

然后在想这个过程的时候,你可能会想的比较复杂,比如,会不会出现连续十几个一样的数字,比如1111111111,读作“ten 1”,然后转换成101。实际上,有大神已经证明,这个序列里的数不会超过4。这边搬运了一下。 原链接:

https://leetcode.com/discuss/6762/how-to-proof-the-count-is-always-less-than-10