新农上路
- 积分
- 98
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-2-13
- 最后登录
- 1970-1-1
|
可以递归处理
- public static void main(String[] args){
- equals(parser("5:Helloi5e"), "[Hello, 5]");
- equals(parser("l5:Helloi5ee"), "[[Hello, 5]]");
- equals(parser("l5:Helloi5ee5:GGGGG"), "[[Hello, 5], GGGGG]");
- equals(parser("ll5:Helloi5ee5:GGGGGe"), "[[[Hello, 5], GGGGG]]");
- }
- private static void equals(List res, String s) {
- System.out.println(res.toString());
- if (!res.toString().equals(s)){
- throw new RuntimeException("bad result.");
- }
- }
- static List<Object> parser(String str) {
- List<Object> buff = new ArrayList<>();
- parse(buff, str, 0, null);
- return buff;
- }
- static int parse(List result, String str, int currentIdx, Character expecting){
- while (currentIdx < str.length() ) {
- char ch = str.charAt(currentIdx);
- if (expecting!=null && expecting.charValue() == ch){
- break;
- }
- if (ch == 'i'){
- currentIdx = parseInt(result, str, currentIdx);
- }else
- if (ch == 'l'){
- currentIdx = parseList(result, str, currentIdx);
- }else
- if (Character.isDigit(ch)) {
- int num = 0;
- int i = 0;
- for (i = currentIdx; i < str.length(); i++) {
- if (!Character.isDigit(str.charAt(i))) {
- break;
- }
- num = num * 10 + (ch - '0');
- }
- //str.charAt(i) == ":"
- currentIdx = parseString(result, str, num, i);
- }
- }
- return currentIdx;
- }
- private static int parseList(List result, String str, int currentIdx) {
- currentIdx ++ ;
- List currentResult = new ArrayList();
- currentIdx = parse(currentResult, str, currentIdx, 'e');
- currentIdx ++ ;
- result.add(currentResult);
- return currentIdx;
- }
- private static int parseInt(List result, String str, int currentIdx) {
- int end = str.indexOf('e', currentIdx);
- result.add(str.substring(currentIdx+1, end));
- return end+1;
- }
- private static int parseString(List result, String str, int leng, int startIdx) {
- //startIdx = ':'
- String res = str.substring(startIdx+1, startIdx + 1 + leng);
- result.add(res);
- //next character
- return startIdx + 1 + leng;
- }
复制代码 |
|