-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix01.java
More file actions
90 lines (55 loc) · 2.19 KB
/
LongestCommonPrefix01.java
File metadata and controls
90 lines (55 loc) · 2.19 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.erikaax.algoritmsleetcode;
import java.util.Arrays;
import java.util.Collections;
/**
*
* @author Erika AX
*/
/*
PROBLEM:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
*/
public class LongestCommonPrefix01 {
public static void main(String[] args) {
String[] strs = {"a", "ab"};
String firstWord = strs[0];
int numIteration = 0;
String response = "";
if(firstWord.isEmpty()) response = "";
if(strs.length == 1 && !firstWord.isEmpty()) response = String.valueOf(firstWord.charAt(0));
for (int i = 0; i < firstWord.toCharArray().length; i++) {
if (firstWord.toCharArray().length == 1) {
for(String word : strs){
if (numIteration == strs.length) break;
if (word.contains(String.valueOf(firstWord.charAt(0)))) {
numIteration++;
response = String.valueOf(firstWord.charAt(0));
}else {
response = "";
break;
}
}
String currentWords = String.valueOf(firstWord.charAt(i)) + String.valueOf(firstWord.charAt(i + 1));
System.out.println(currentWords);
for(String word : strs){
if (numIteration == strs.length) break;
if (word.contains(currentWords)) {
numIteration++;
response = currentWords;
}else {
response = "";
break;
}
}
}
System.out.println(response);
}}
}