Re: [閒聊] 每日leetcode

看板Marginalman作者 (早瀬ユウカの体操服 )時間1年前 (2024/12/17 21:17), 編輯推噓1(101)
留言2則, 2人參與, 1年前最新討論串1210/1554 (看更多)
https://leetcode.com/problems/construct-string-with-repeat-limit 2182. Construct String With Repeat Limit 給你一個字串s和一個整數repeatLimit,你可以從s取任意數量的字元一次構建成 一個新的字串,每個相鄰字元數量不可超過repeatLimit次,求出字典序最大的字串 怎麼組。 思路: 1.先數每個字母的數量,然後每次都拿字母最大的字插入 MIN(count, repeatLimit)個 ,然後拿第二個大的字母append到最大的字串尾,不斷循環直到沒辦法拿第二大的字 母。 Java Code --------------------------------------------------------------------- class Solution { public String repeatLimitedString(String s, int repeatLimit) { int[] count = new int[26]; for (char c : s.toCharArray()) { count[c - 'a']++; } StringBuilder sb = new StringBuilder(); int i = 25; int prev = -1; while (i >= 0) { // 如果最大字典用完就往次大 if (count[i] == 0) { i--; continue; } // 如果最大已經用過,插入一個次小的 if (i == prev) { int j = i - 1; while (j >= 0) { if (count[j] > 0) break; j--; } if (j == -1) break; sb.append((char) ('a' + j)); count[j] -= 1; } // append repeatLimit次 int times = Math.min(repeatLimit, count[i]); for (int k = 0; k < times; k++) { sb.append((char) ('a' + i)); } count[i] -= times; prev = i; } return sb.toString(); } } --------------------------------------------------------------------- -- 你跟我說這個我有什麼辦法 https://i.imgur.com/wb5zrOy.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.158.191.3 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1734441439.A.8E6.html

12/17 21:21, 1年前 , 1F
大師
12/17 21:21, 1F

12/17 21:21, 1年前 , 2F
大師
12/17 21:21, 2F
文章代碼(AID): #1dONdVZc (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1dONdVZc (Marginalman)