-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay47.java
More file actions
48 lines (34 loc) · 1.05 KB
/
Day47.java
File metadata and controls
48 lines (34 loc) · 1.05 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
48
import java.util.Scanner;
public class Day47 {
public static String longestCommonPrefix(String[] arr) {
if (arr.length == 0) {
return "";
}
String prefix = arr[0];
for (int i = 1; i < arr.length; i++) {
int j = 0;
while (j < prefix.length() && j < arr[i].length() && prefix.charAt(j) == arr[i].charAt(j)) {
j++;
}
prefix = prefix.substring(0, j);
if (prefix.equals("")) {
break;
}
}
return prefix;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0) {
int n = scanner.nextInt();
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.next();
}
String result = longestCommonPrefix(arr);
System.out.println(result);
}
scanner.close();
}
}