在office软件(word,excel)中,有时只需要打印整个文档中的一部分,就需要用户选择需要打印的页码范围。目前输入的页码范围格式定义为:以逗号分割,可以使用-表示连续页码。例如:1,3,5-9,20。表示需要打印的页码为1,3,5,6,7,8,9,20。
本题目要求读入一行字符串,作为需要打印的页码范围。需要注意以下几点:
-
1、页码范围输入可以不按顺序。例如:5,3,7,9-10,1-2;
-
2、连续的页码定义也可能不会按照由小到大的顺序输入。例如:1,9,5,20-15,10;
-
3、输入的页码范围可能会有重复。例如:1,9,15,5-10,12-20;
输入格式:
第一行:表示页码范围的格式化字符串
输出格式:
将需要打印的页码按照由小到大的顺序输出,以空格分割
输入样例:
1,3,5-9,20
输出样例:
1 3 5 6 7 8 9 20
输入样例:
12-20,1,15,9,5-10
输出样例:
1 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20
首先将这个字符串按行读入,然后用空格将它分割成若干个字符串,对每一个字符串去做判断,如果存在 '-'说明是打印一个区间的,那么将这个区间的页码记录,否则就直接是一个单独页码,由于会出现页码重复或者乱序,那么利用TreeSet容器去重排序即可。
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
TreeSet<Integer> s = new TreeSet<>();
String str = cin.nextLine();
String [] t = str.split(",");
for(int k = 0;k < t.length;k++){
int x = 0,n = t[k].length(),y = 0;
int id = -1;
for(int i = 0;i < n;i++){
char num = t[k].charAt(i);
if(num == '-'){
id = i;
break;
}
x = x * 10 + (int)num - 48;
}
if(id != -1){
for(int i = id+1;i < n;i++){
char num = t[k].charAt(i);
y = y * 10 + (int)num - 48;
}
if(x > y){
int tem = x;
x = y;
y = tem;
}
for(int i = x;i <= y;i++){
s.add(i);
}
}
else{
s.add(x);
}
}
Iterator<Integer> it = s.iterator();
int cnt = 0;
while(it.hasNext()){
if(cnt == 0){
System.out.print(it.next());
}
else{
System.out.print(" "+it.next());
}
cnt++;
}
}
}