'字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。 '示例: '输入: s = "ababcbacadefegdehijhklij" '输出:[9,7,8] 解释: 划分结果为 "ababcbaca", "defegde", "hijhklij"。 每个字母最多出现在一个片段中。 像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。 Public list As New Collection Sub 贪心算法_划分字母区间() te = VBA.Asc("a") s = "ababcbacadefegdehijhklij" Call partitionLabels(s) For Each e In list Debug.Print e Next Set list = Nothing End Sub Public Sub partitionLabels(s) chars = toCharArray(s) Dim edge(25) For i = 0 To UBound(chars) Index = VBA.Asc(chars(i)) - VBA.Asc("a") edge(Index) = i Next idx = 0 last = -1 For i = 0 To UBound(chars) idx = Application.Max(idx, edge(VBA.Asc(chars(i)) - VBA.Asc("a"))) If i = idx Then list.Add (i - last) last = i End If Next End Sub Function toCharArray(s) Dim arr() For x = 1 To Len(s) ReDim Preserve arr(0 To x - 1) arr(x - 1) = Mid(s, x, 1) Next toCharArray = arr End Function
标签:VBA,arr,chars,片段,Next,Asc,算法,字母,贪心 From: https://www.cnblogs.com/eyunkeji/p/16971531.html