Leet Code OJ 38. Count and Say [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 38. Count and Say [Difficulty: Easy]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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.
翻譯:
這個”計算并說出“的序列是一個整數序列,開始于下列這樣:
1, 11, 21, 1211, 111221, …
1 讀作 “1個1” 或者 11.
11 讀作”2個1” 或者 21.
21 讀作”1個2, 然后1個1” 或者 1211.
給定一個整數n,產生第n個序列。
分析:
這道題目的意思,需要仔細看一下才能看懂,簡單來說,n=1的時候返回”1”,n>1的時候,對n-1返回的值按照類似”21->1211“這種讀出的方式處理后,將結果返回。
代碼:
public class Solution {public String countAndSay(int n) {String str="1";for(int i=1;i<n;i++){char[] arr=str.toCharArray();str="";int count=0;char current='1';for(char c:arr){if(c==current){count++;}else{if(count!=0){str+=""+count+current;}count=1;current=c;}}if(count!=0){str+=""+count+current;}}return str;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 38. Count and Say [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 168. Ex
- 下一篇: Leet Code OJ 7. Reve