例如,输入数组为:
String array = {"0","0","0","K","K","B","P","P","P","Z",
"Z","D","D","E","E","F","N","O","O}输出:
first sub-array = {"O,O,O"}
second sub-array = {"K","K"}
third sub-array = {"O","O"}发布于 2019-11-29 18:25:56
你可以使用下面的代码中的stack来完成这项工作。
String data[] = { "0", "0", "0", "K", "K", "B", "P", "P", "P", "Z", "Z", "D", "D", "E", "E", "F", "N" };
// a = ['0','0','0','K','K','P','P','P','Z']
Stack<String> stack = new Stack<String>();
String prevValue = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i].equals(data[i - 1])) {
prevValue = prevValue + data[i];
} else {
stack.push(prevValue);
prevValue = data[i];
}
}
stack.push(prevValue);
System.out.println(stack);发布于 2019-11-29 17:28:37
假设您不知道要查找多少个不同的字符,一种可能的解决方案是使用Map:
Map<String,List<String>> map = new HashMap<>();
for(int i = 0; i < array.length; i++){
if(map.containsKey(array[i])
map.get(array[i]).add(array[i]);
else
map.put(array[i],array[i]);
}但是,就我个人而言,我认为使用参数样式方法可以简化您的要求。这就是说,不是存储每个字符串模式的每次出现,而是简单地存储一个计数器。所以,仍然假设你不知道你在寻找多少不同的模式,你可以这样做:
Map<String,Integer> map = new HashMap<>();
for(int i = 0; i < array.length; i++){
map.put(array[i], new Integer(map.get(array[i]).intValue() + 1);
}发布于 2019-11-29 17:20:19
如果你正在寻找连续的区域,你可以使用循环,因为顺序很重要。
List<List<String>> continuous = new ArrayList<>();
List<String> current;
String last = null;
for(String s: array){
if(!s.equals(last)){
current = new ArrayList<>();
continuous.add(current);
}
current.add(s);
last=s;
}在您的示例中,您可以使用流和grouping by收集器,因为区域也是唯一的字符。
Map<String, List<String>> grouped = Arrays.stream(array).collect(
Collectors.groupingBy(String::toString)
);如果你真的需要String[]而不是List,你可以使用List.toArray。
String[] arr_version = grouped.get("0").toArray(new String[0]);https://stackoverflow.com/questions/59100733
复制相似问题