-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
25 lines (22 loc) · 751 Bytes
/
Copy pathMain.java
File metadata and controls
25 lines (22 loc) · 751 Bytes
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
// leetcode problem: https://leetcode.com/problems/longest-common-prefix/
class Solution {
public String longestCommonPrefix(String[] strs) {
String prefix = strs[0];
for(int i=1; i<strs.length; i++){
while(!strs[i].startsWith(prefix)){
prefix = prefix.substring(0, prefix.length()-1);
if(prefix == "")
return "";
}
}
return prefix;
}
}
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
String[] strs = {"flower", "flow", "flight"};
String result = solution.longestCommonPrefix(strs);
System.out.println("Longest Common Prefix: " + result);
}
}