
输入一行单词序列,相邻单词之间由1个或多个空格间隔,请按照字典序输出这些单词,要求重复的单词只输出一次。(区分大小写)
输入一行单词序列,最少1个单词,最多100个单词,每个单词长度不超过50,单词之间用至少1个空格间隔。数据不含除字母、空格外的其他字符。
输出按字典序输出这些单词,重复的单词只输出一次。
样例输入样例输出She wants to go to Peking University to study Chinese
Chinese
Peking
She
University
go
study
to
wants
思路分析
.此题思路比较简单,按照字典顺序排序就是按照首字母排序。
1.对输入进来的数据进行处理存进一个字符数组。
2.实现对每个单词通过字符ASCII差值进行计算得出其大小
3.对字符数组按照第二得出的大小进行排序即可
代码实现
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
String[] strs = new String[100];
String code = "";
int index = 0;
int length = 0;
for (int i = 0; i < str.length(); i++) {
if (i == str.length()-1){
code+=str.charAt(i);
strs[index++] = code;
length++;
break;
}
if (str.charAt(i)!=' '){
code+=str.charAt(i);
}
else if (str.charAt(i)==' '&&str.charAt(i-1) != ' '){ //空格处理
strs[index++] = code;
length++;
code = "";
}
}
//System.out.println(Arrays.toString(strs));
Sort(strs,length);
System.out.println(strs[0]);
for (int i = 1; i < length; i++) {
if (!strs[i] .equals( strs [i-1]))
System.out.println(strs[i]);
}
}
public static void Sort(String[] strs, int length) {
//插入排序
for (int i = 0; i < length-1; i++){
String insertVal = strs[i+1]; //待插入元素
int insertIndex = i ; //待插入的下标
int charIndex = 0;
//找到插入位置
while (insertIndex >= 0 && insertVal!=null&& !codeCom(insertVal,strs[insertIndex])){
strs[insertIndex+1] = strs[insertIndex];
insertIndex--;
}
//当退出循环则说明找到插入的位置了
strs[insertIndex + 1] = insertVal;
}
}
//单词比较大小
public static boolean codeCom(String code1,String code2){
int min = Math.min(code1.length(), code2.length());
boolean flag = false;
if (min == code2.length()) flag=true;
for (int i = 0; i < min; i++) {
if (code1.charAt(i) > code2.charAt(i)) {
return true;
}else if (code1.charAt(i) == code2.charAt(i)) {
continue;
}else{
return false;
}
}
if (!flag) {
return false; //code1 小于 code2
}
return true;
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)