Re: [閒聊] 每日leetcode

看板Marginalman作者 (早瀬ユウカの体操服 )時間8月前 (2025/03/31 01:10), 編輯推噓1(100)
留言1則, 1人參與, 8月前最新討論串1377/1548 (看更多)
https://leetcode.com/problems/partition-labels 763. Partition Labels 給你一個字母字串,可以把該字串切成n段子字串,任意字母只能出現在一段,且 盡量切成越多段越好,求出每段的長。 思路: 類似前幾天的區間問題,把每個字母第一次出現和最後一次出現的索引當成區間, 然後把交錯的區間合併,到下個區間的時候把區間長記錄起來就好。 Java Code: ------------------------------------------------- class Solution { public List<Integer> partitionLabels(String s) { int[] last = new int[26]; for (int i = 0; i < s.length(); i++) { last[s.charAt(i) - 'a'] = i; } List<Integer> res = new ArrayList<>(); int start = 0; int end = 0; for (int i = 0; i < s.length(); i++) { end = Math.max(end, last[s.charAt(i) - 'a']); if (i == end) { res.add(end - start + 1); start = i + 1; } } return res; } } ------------------------------------------------- -- https://i.imgur.com/ZUx84aU.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.158.101.161 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1743354649.A.0D9.html

03/31 01:48, 8月前 , 1F
大師 我哭了
03/31 01:48, 1F
文章代碼(AID): #1dwNiP3P (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1dwNiP3P (Marginalman)