精華區beta Marginalman 關於我們 聯絡資訊
38. Count and Say 數數之後組成下一個字串,直接看例子: https://assets.leetcode.com/uploads/2020/10/23/countandsay.jpg
n = 1: return 1 is the base case n = 2: return count of last entry i.e. 1 1 n = 3: return count of last entry i.e. two 1's so 21 n = 4: we have one 2 and one 1 so 1211 n = 5: , we have one 1 and one 2 and two 1's so -> 111221 n = 6: we have three 1's, two 2's and one 1 so -> 312211 n = 7: we have one 3, one 1, two 2's and two 1's -> 13112221 思路: 1.每輪從第一個字往後數共有幾個連續數字。 2.把該輪從左到右把{數量}{數字}通通串接起來就是i+1的新字串。 3.從2跑到n執行 n - 1次 JavaCode: class Solution { public String countAndSay(int n) { String str = "1"; StringBuilder sb = new StringBuilder(); for(int i = 2; i <= n; i++) { int j = 0, len = str.length(); while (j < len) { char c = str.charAt(j); int count = 0, k = j; while (k < len && c == str.charAt(k++)) count++; sb.append(count).append(c); j += count; } str = sb.toString(); sb.setLength(0); } return str; } } 白癡閱讀測驗題目 花10分鐘看題目花三分鐘解題目= = 今天好忙 終於有時間可以打混偷寫LeetCode -- https://i.imgur.com/tdaniED.jpg -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.160.90.182 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1666082279.A.590.html ※ 編輯: Rushia (1.160.90.182 臺灣), 10/18/2022 16:40:34
JerryChungYC: 大師 10/18 16:50