本文主要是介绍[LeetCode] 763. Partition Labels,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题:https://leetcode.com/submissions/detail/187840512/
题目
A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
Note:
- S will have length in range [1, 500].
- S will consist of lowercase letters (‘a’ to ‘z’) only.
题目大意
将字符串 分为多份。一个字母至多只能出现在 一个 部分中,求划分的最多部分。
思路
贪心思路
class Solution {public List<Integer> partitionLabels(String S) {int[] finalyIndex = new int[26];int slen = S.length();for(int i = 0 ; i<slen;i++)finalyIndex[S.charAt(i)-'a'] = i;List<Integer> res = new ArrayList<>();int index = 0;int tres = 0;for(int i = 0 ; i<slen;i++){index = Math.max(index,finalyIndex[S.charAt(i)-'a']);tres++;if(index == i){res.add(tres);tres = 0;}}return res;}
}
这篇关于[LeetCode] 763. Partition Labels的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!