題目描述:
給你一個字符串 s
。我們要把這個字符串劃分為盡可能多的片段,同一字母最多出現在一個片段中。
注意,劃分結果需要滿足:將所有劃分結果按順序連接,得到的字符串仍然是 s
。
返回一個表示每個字符串片段的長度的列表。
初始代碼:
class Solution {public List<Integer> partitionLabels(String s) {}
}
示例1:
輸入:s = "ababcbacadefegdehijhklij" 輸出:[9,7,8] 解釋: 劃分結果為 "ababcbaca"、"defegde"、"hijhklij" 。 每個字母最多出現在一個片段中。 像 "ababcbacadefegde", "hijhklij" 這樣的劃分是錯誤的,因為劃分的片段數較少。
示例2:
輸入:s = "eccbbbbdec" 輸出:[10]
參考答案:
class Solution {public List<Integer> partitionLabels(String s) {List<Integer> list = new ArrayList<>();// 使用Hash表的唯一值增加增快效率Set<Character> set = new HashSet<>();// 定義雙指針int left = 0;int right = 0;// 記錄前一個左指針位置int count = 0;while (left < s.length()) {// 截取字符串進而繼續遍歷其中的字符right = s.lastIndexOf(s.charAt(left));for (int i = left; i < right; ++i) {if (!set.add(s.charAt(i))) {continue;}right = Math.max(right, s.lastIndexOf(s.charAt(i)));}// 左指針位移left = right + 1;list.add(left - count);count = left;}return list;}
}