题解 | #参数解析#

参数解析

https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677

不知道用例里需要保证顺序.. 浪费了时间。

而且一开始没有想好具体的方案,还需要调试。

一共花费大概1小时40分钟。

时间用得比较久...

考虑过逐个字符来比较,遇到第一个引号和后一个匹配的引号取出值来,发现这样直接,没有办法判断第一个和后一个的位置;

考虑过用别的字符替换引号,测试过后发现这个想法还是不能解决全部的问题;

最后采用替换加取引号内内容的方法弄出来了。

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * 参数解析
 * xcopy~/s~"C:\\program~files"~"d:\"
 * xcopy /s "C:\\program files" "d:\"
 */
public class ParamParse {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String nextLine = scanner.nextLine();
            List<String> result = new ArrayList<>();
            LinkedList<Integer> locations = new LinkedList<>();
    
            while (true) {
                int indexOf = nextLine.indexOf("\"");
                if (indexOf != -1) {
                    nextLine = nextLine.replaceFirst("\"", "!");
                    locations.add(indexOf);
                } else {
                    break;
                }
            }
            
            List<String> quetList = new ArrayList<>();
            while (!locations.isEmpty()) {
                Integer beforeIndex = locations.pop();
                Integer afterIndex = locations.pop();
                quetList.add(nextLine.substring(beforeIndex + 1, afterIndex));
            }
            nextLine = nextLine.replace(" ", "~");
            String[] split = nextLine.split("!");
    
            for (String str : split) {
                if (!str.equals("~")) {
                    String replaceOtherStr = str.replace("~", " ");
                    if (quetList.contains(replaceOtherStr)) {
                        // 为保证顺序,包含就加入到result中
                        result.add(replaceOtherStr);
                        
                    } else {
                        String[] splitOther = replaceOtherStr.split(" ");
                        for (String s : splitOther) {
                            if (s.equals(" ") || s.length() == 0) {
                                continue;
                            } else {
                                result.add(s);
                            }
                        }
                    }
                }
            }
            System.out.println(result.size());
            for (String str : result) {
                System.out.println(str);
            }
        }
    }
}

全部评论

相关推荐

迟缓的斜杠青年巴比Q了:简历被投过的公司卖出去了,我前两天遇到过更离谱的,打电话来问我有没有意向报班学Java学习,服了,还拿我学校一个学长在他们那报班学了之后干了华为OD当招牌
点赞 评论 收藏
分享
刘湘_passion:太强了牛肉哥有被激励到
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务