开发者社区> 问答> 正文

如何将此数组分解为类似字母类型的子数组(在连续位置)

例如,输入数组为:

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"}

展开
收起
垚tutu 2019-11-29 19:53:25 920 0
1 条回答
写回答
取消 提交回答
  • #include

    您可以在下面的代码中使用堆栈进行结帐。

    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 19:53:38
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载