前言
经过前期的数据结构和算法学习,开始以OD机考题作为练习题,继续加强下熟练程度。
描述
在命令行输入如下命令:
xcopy /s c:\\ d:\\e,
各个参数如下:
参数1:命令字xcopy
参数2:字符串/s
参数3:字符串c:\\
参数4: 字符串d:\\e
请编写一个参数解析程序,实现将命令行各个参数解析出来。
解析规则:
1.参数分隔符为空格
2.对于用""包含起来的参数,如果中间有空格,不能解析为多个参数。比如在命令行输入xcopy /s "C:\\program files" "d:\"时,参数仍然是4个,第3个参数应该是字符串C:\\program files,而不是C:\\program,注意输出参数时,需要将""去掉,引号不存在嵌套情况。
3.参数不定长
4.输入由用例保证,不会出现不符合要求的输入
数据范围:字符串长度:1≤𝑠≤1000 1≤s≤1000
进阶:时间复杂度:𝑂(𝑛) O(n) ,空间复杂度:𝑂(𝑛) O(n)
输入描述:
输入一行字符串,可以有空格
输出描述:
输出参数个数,分解后的参数,每个参数都独占一行
示例1
输入:
xcopy /s c:\\ d:\\e输出:
4 xcopy /s c:\\ d:\\e
实现原理与步骤
1.记录要输出的参数的下标位置。
2.如果下标位置不连续则进行分割并输出。
实现代码
import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别String cmd = in.nextLine();List<Integer> list = new ArrayList();boolean flag = false;for (int i = 0; i < cmd.length(); i++) {if (cmd.charAt(i) == '"') {flag = !flag;}else if (cmd.charAt(i) != ' ' || flag) {list.add(i);}}int begin = -1;int pre = -1;List<String> res = new ArrayList();for (int i = 0; i < list.size(); i++) {//初始化字符串分割起点和移动下标的前一位置下标if (begin == -1) {begin = list.get(i);pre = begin;continue;}if (list.get(i) == pre + 1) {pre = list.get(i);} else {res.add(cmd.substring(begin, pre + 1));//重置字符串分割起点和移动下标的前一位置下标begin = list.get(i);pre = begin;}}//加入剩余字符res.add(cmd.substring(begin, pre + 1));//输出参数System.out.println(res.size());for (String str : res) {System.out.println(str);}}
}
实现代码(正则匹配法)
import java.util.*;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别String cmd = in.nextLine();// 使用正则表达式分割,保留双引号内的内容String[] result = cmd.split(" (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");System.out.println(result.length);for (String s : result) {// 去除分割后保留的双引号s = s.replaceAll("^\"|\"$", "");System.out.println(s);}}
}