通行证
- 积分
- 743
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-1-12
- 最后登录
- 1970-1-1
|
第二题:sorting nested dictionary
我本来截图了的···,可是发现发图好麻烦啊···,就不发图了,我把题意说一下:
给一个字符串,字符串里面的每一个元素都是一个键值对,有key和value,例如 a:apple 或者c:change 值可以嵌套:例如 b:{cb:cranbery,bb:bluberry,bd:{}},嵌套的大括号里面可以为空。
要求按照key将所有的键值对排序,再返回一个新的String;
例如输入字符串:{b:{cb:cranberyy,bb:blueberry},a:apple,c:cherry}
返回字符串:{a:apple,b:{bb:blueberry,cb:cranbery},c:cherry}
即先把内层的{}按key排好序,再以此把外层排序。题目保证输入数据是合法的,开始和结束字符一定是'{' 和 '}'
楼主自己也比较水,拿到这个题刚开始一脸懵逼,感觉应该是递归,后来写了半天也写不对,最后想用着用正常的循环遍历做,后来来不及了。下来之后在codepad上接着写完了,试跑了两组数据没问题,不过不知道最后能不能过,只能作参考:
- class Solution {
- public static void main(String[] args) {
- String input = "{b:{cb:{cbz:cbzkk,cba:{cbad:cranberry,cbac{}}},bb:blueberry},a:apple,c:cherry}";
- sort_entries(input);
- }
- /*
- * Complete the function below.
- */
- static void sort_entries(String input) {
- char[] arr = input.toCharArray();
- int len = arr.length;
- Stack<Integer> stack = new Stack<>();
- for (int i = 0; i < len; i++) {
- if (arr[i] == '{') {
- stack.push(i);
- } else if (arr[i] == '}') {
- sort(arr, stack.pop() + 1, i - 1);
- }
- }
- //return arr.toString();
- System.out.println( String.valueOf(arr));
- }
- public static void sort (char[] arr, int start, int end) {
- if (start >= end) {
- return ;
- }
- List<String> temp = new ArrayList<>();
- StringBuilder builder = new StringBuilder();
- Stack<Integer> stack = new Stack<>();
- for (int i = start; i <= end; i++) {
- if (arr[i] == '{') {
- stack.push(i);
- }
- if (arr[i] == '}') {
- stack.pop();
- }
- if (arr[i] == ',' && stack.isEmpty()){
- temp.add(builder.toString());
- builder = new StringBuilder();
- continue;
- }
- builder.append(arr[i]);
- }
- temp.add(builder.toString());
- Collections.sort(temp);
- int index = start;
- for(int i = 0; i < temp.size(); i++) {
- for(int j = 0; j < temp.get(i).length(); j++) {
- arr[index++] = temp.get(i).charAt(j);
- }
- if(i != temp.size() - 1) {
- arr[index++] = ',';
- }
- }
- }
复制代码
|
|