LetCode in Swift (763. Partition Labels)
文章目录
文档更新说明
- 最后更新 2018年03月19日
- 首次更新 2018年03月19日
前言
使用Swift语言完成LetCode题目,中等难度,是一道关于贪心算法的题目,贪心算法的介绍请看文章最底部.
简单说一下,贪心算法的思想就是保证从初始状态开始,算法每一个步骤都是局部最优解,最后得到的结果就是全局最优解.当然并不是所有问题都可以通过贪心算法解决,具体请看文章底部链接.
763. Partition Labels
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
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.
Solution
这道题的意思是说,给一个字符串,让我们分割成尽量多个部分(Parts),保证每一个字母都最多出现在其中一个Part里面.
我下面做出来的结果是Accepted的,但是比90%的人都慢了😂,算法应该有很大的优化空间,这里就不多说了,毕竟这道题没有超时,说明我的解法是被认可的🙈.
1 | import Foundation |