-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString19.java
More file actions
47 lines (38 loc) · 1.15 KB
/
String19.java
File metadata and controls
47 lines (38 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.*;
public class String19 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
String[] words = new String[n];
for (int i = 0; i < n; i++) {
words[i] = sc.nextLine();
}
String prefix = "";
if (n > 0) {
prefix = words[0];
for (int i = 1; i < n; i++) {
while (!words[i].startsWith(prefix)) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
break;
}
}
}
}
System.out.print("Strings: [");
for (int i = 0; i < n; i++) {
System.out.print(words[i]);
if (i != n - 1) {
System.out.print(", ");
}
}
System.out.println("]");
if (prefix.isEmpty()) {
System.out.println("Longest Common Prefix: (empty)");
} else {
System.out.println("Longest Common Prefix: " + prefix);
}
sc.close();
}
}