forked from alexkoby/Leetcode-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest Common Prefix
More file actions
39 lines (33 loc) · 1.01 KB
/
Longest Common Prefix
File metadata and controls
39 lines (33 loc) · 1.01 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
//Completed 4/25/18 --
// Longest Common Prefix
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
{
return "";
}
int spotShortestString = 0;
int lengthShortestString = strs[0].length();
for(int i = 0; i < strs.length; i++)
{
if(strs[i].length() < lengthShortestString)
{
spotShortestString = i;
lengthShortestString = strs[i].length();
}
}
int howManyCharacters = 0;
for(int i = 0; i < lengthShortestString; i++)
{
for(int j = 0; j < strs.length; j++)
{
if(strs[j].charAt(i) != strs[spotShortestString].charAt(i))
{
return strs[spotShortestString].substring(0, howManyCharacters);
}
}
howManyCharacters++;
}
return strs[spotShortestString];
}
}