程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode解題報告-- Count and Say

LeetCode解題報告-- Count and Say

編輯:C++入門知識

LeetCode解題報告-- Count and Say


題目:

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.
點擊解題:Count and Say

分析:題意是要求通過程序生成一組符合題意要求的字符串,
題目難度不高,基本思路是:以n為例,直接從左向右掃描n-1字符串,計算出現相同數字的個數 ,直至掃描結束!示意圖如下:初始:count = 1,,每遇到數字相同,count++,然後將count轉為字符串或字符類型 + 當前數組字符 以此為規律找出nth字符串。
這裡寫圖片描述

java代碼: Accepted

public class Solution {
    public String countAndSay(int n) {
       String newS = "1";
       int count = 1;
       int i = 1;
       while(i < n){
           String s = newS;
           newS = "";
           for(int j = 0;j < s.length();j ++){
                if( (j + 1) < s.length() && s.charAt(j) == s.charAt(j + 1)){
                    count ++;
                }else{
                    newS = newS + count + s.charAt(j);
                    count = 1;
                }
            }
            i ++;
       }
       return newS;
    }
}

python代碼 Accepted

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        i = 1
        count = 1
        newS = "1"

        while i < n:
            s= newS
            newS = ""

            for j in range(len(s)):
                if((j + 1) < len(s) and s[j] == s[j + 1]):
                    count = count + 1
                else:
                    newS = newS + str(count) + s[j]
                    count = 1
            i = i + 1
        return newS

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved