24 lines
734 B
Java
24 lines
734 B
Java
package com.zerroi.leetcode.Three14;
|
|
|
|
public class LongestCommonPrefix {
|
|
public static void main(String[] args) {
|
|
SolutionFirst solutionFirst = new SolutionFirst();
|
|
String res = solutionFirst.longestCommonPrefix(new String[]{"flower", "flow", "flight"});
|
|
System.out.println("res = " + res);
|
|
}
|
|
}
|
|
|
|
class SolutionFirst {
|
|
public String longestCommonPrefix(String[] strs) {
|
|
if (strs.length == 0) return "";
|
|
String prefix = strs[0];
|
|
for (String str : strs) {
|
|
while (!str.startsWith(prefix)) {
|
|
if (prefix.length() == 0) return "";
|
|
prefix = prefix.substring(0, prefix.length() - 1);
|
|
}
|
|
}
|
|
return prefix;
|
|
}
|
|
}
|