• 欢迎光临~

报文解析

开发技术 开发技术 2022-06-07 次浏览

将字符串中的n[str]转换为n个str拼接,例如输入:3[m2[c]1[b]],则输出 mccbmccbmccb

 1 package org.example.test;
 2 
 3 import javafx.util.Pair;
 4 
 5 import java.util.LinkedList;
 6 import java.util.Scanner;
 7 
 8 public class Main {
 9     public static void main(String[] args) {
10         Scanner scanner = new Scanner(System.in);
11         String s = scanner.next();
12         scanner.close();
13         System.out.println(convert(s, 0, s.length()));
14     }
15     
16     public static String convert(String s, int start, int end) {
17         LinkedList<Pair<Integer, Integer>> list = new LinkedList<>();
18         int p, q = start - 1;   // p为'['的索引  q为']'的索引
19         while (true) {
20             p = s.indexOf('[', q + 1);
21             if (p == -1 || p >= end) {
22                 break;
23             }
24             q = match(s, p);
25             list.add(new Pair<>(p, q));
26         }
27         StringBuilder sb = new StringBuilder();
28         int lastQ = start - 1;
29         for (Pair<Integer, Integer> pair : list) {
30             p = pair.getKey();
31             q = pair.getValue();
32             int i = p - 1;
33             while (i >= start && Character.isDigit(s.charAt(i))) {
34                 i--;
35             }
36             int num = Integer.parseInt(s.substring(i + 1, p));
37             String convert = convert(s, p + 1, q);
38             if (i > lastQ) {
39                 sb.append(s, lastQ + 1, i + 1);
40             }
41             for (int j = 0; j < num; j++) {
42                 sb.append(convert);
43             }
44             lastQ = q;
45         }
46         return list.isEmpty() ? s.substring(start, end) : sb.append(s, list.getLast().getValue() + 1, end).toString();
47     }
48 
49     /**
50      * 查找'['匹配的']'的索引
51      * @param s 字符串
52      * @param p '['的索引
53      * @return 匹配的']'的索引
54      */
55     public static int match(String s, int p) {
56         int counter = 1;
57         for (int q = p + 1; q < s.length(); q++) {
58             if (s.charAt(q) == '[') {
59                 counter++;
60             } else if (s.charAt(q) == ']') {
61                 counter--;
62             }
63             if (counter == 0) {
64                 return q;
65             }
66         }
67         return -1;
68     }
69 }

 

程序员灯塔
转载请注明原文链接:报文解析
喜欢 (0)