LeetCode/com/zerroi/leetcode/Three14/LongestCommonPrefix.java

24 lines
734 B
Java
Raw Normal View History

2024-03-14 20:58:23 +08:00
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;
}
}