import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型一维数组
*/
public int[] partition_cows (String s) {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < s.length();) {
int index = s.lastIndexOf(s.charAt(i));
if (index == -1) {
// 找不到字符,就直接切片为1
arrayList.add(1);
i++;
} else {
// 如果找的到字符
int start = i + 1, end = index;
while (start < end) {
end = Math.max(end, s.lastIndexOf(s.charAt(start)));
start++;
}
arrayList.add(end - i + 1);
i = end + 1;
}
}
int [] result = new int[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
result[i] = arrayList.get(i);
}
return result;
}
}
本题知识点分析:
1.有序集合
2.数学模拟
3.集合转数组
本题解题思路分析:
1.创建集合存储结果(因为大小未知)
2.如果取出的字符在字符串中出现一次,直接切片1,然后i++
3.如果取出的字符在字符串至少出现2次,得到最后一个出现的位置end
4.遍历从start到end的所有字符,每次去更新end,检查是否所有中间的字符都能被包含在内
5.最后end-i+1就是切片的长度,更新i = start+1,下一次开始切片的位置
本题使用编程语言: Java
如果你觉得本篇文章对你有帮助的话,可以点个赞支持一下,感谢~

京公网安备 11010502036488号