這題計算連續字符串,組成為 重複次數+數字。
LeetCode 題目連結
https://leetcode.com/problems/count-and-say/
題目
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note: Each term of the sequence of integers will be represented as a string.
Accept 作法
Runtime: 12 ms
Memory: 40.2 MB
Java 程式碼
class Solution { public String countAndSay(int n) { if(n == 0){ return null; } int i =1; String ans = "1"; while(i < n){ StringBuilder builder = new StringBuilder(); int count = 1; for(int j = 0; j < ans.length(); j++){ if(j < ans.length() - 1 && ans.charAt(j) == ans.charAt(j+1)){ count++; }else{ builder.append(count+""+ans.charAt(j)); count = 1; } } ans = builder.toString(); i++; } return ans; } }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言