版权声明:博客内容为本人自己所写,请勿转载。 https://blog.csdn.net/weixin_42805929/article/details/82842840
字串的连接最长路径查找 java
题目描述
给定n个字符串,请对n个字符串按照字典序排列。
输入描述:
输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。
输出描述:
数据输出n行,输出结果为按照字典序排列的字符串。
示例1
输入
9
cap
to
cat
card
two
too
up
boat
boot
输出
boat
boot
cap
card
cat
to
too
two
up
代码1:使用java自带的方法
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] st = new String[n];
for(int i = 0; i < n; i++){
st[i] = sc.next();
}
Arrays.sort(st);
for(int i = 0; i < n; i++){
System.out.println(st[i]);
}
}
}
代码2:使用标志位冒泡排序和compareTo()方法
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] st = new String[n];
for(int i = 0; i < n; i++){
st[i] = sc.next();
}
test(st);
for(int i = 0; i < n; i++){
System.out.println(st[i]);
}
}
public static void test(String[] st){
for(int i = 0; i < st.length - 1; i++){
boolean flag = true;
for(int j = 0; j < st.length- i - 1; j++){
// compareTo(String)-- 按照字典顺序比较字符串大小
if(st[j].compareTo(st[j+1]) > 0){
String temp = st[j];
st[j] = st[j+1];
st[j+1] = temp;
flag = false;
}
}
if(flag == true){
break;
}
}
}
}