Topic
- String
Description
https://leetcode.com/problems/longest-common-prefix/
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.
Constraints:
- 0 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lower-case English letters.
Analysis
略
Submission
public class LongestCommonPrefix {// 方法一:我写的public String longestCommonPrefix1(String[] strs) {if (strs == null || strs.length == 0)return "";StringBuilder sb = new StringBuilder();out: for (int i = 0; i < strs[0].length(); i++) {char current = strs[0].charAt(i);for (int j = 1; j < strs.length; j++) {if (strs[j].length() == i || strs[j].charAt(i) != current)break out;}sb.append(current);}return sb.toString();}// 方法二:public String longestCommonPrefix2(String[] strs) {if (strs == null || strs.length == 0)return "";for (int i = 0; i < strs[0].length(); i++) {char current = strs[0].charAt(i);for (int j = 1; j < strs.length; j++) {if (strs[j].length() == i || strs[j].charAt(i) != current)return strs[0].substring(0, i);}}return strs[0];}// 方法三:public String longestCommonPrefix3(String[] strs) {if (strs == null)return null;if (strs.length == 0)return "";String theShortest = strs[0], theLongest = strs[0];for (String str : strs) {if (str.compareTo(theShortest) < 0)theShortest = str;if (str.compareTo(theLongest) > 0)theLongest = str;}int i = 0;while (i < theShortest.length() && theShortest.charAt(i) == theLongest.charAt(i))i++;return theShortest.substring(0, i);
}
Test
import static org.junit.Assert.*;
import org.junit.Test;public class LongestCommonPrefixTest {@Testpublic void test() {LongestCommonPrefix obj = new LongestCommonPrefix();final String[] array1 = {"flower", "flow", "flight"};assertEquals("fl", obj.longestCommonPrefix1(array1));assertEquals("fl", obj.longestCommonPrefix2(array1));assertEquals("fl", obj.longestCommonPrefix3(array1));final String[] array2 = {"dog", "racecar", "car"};assertEquals("", obj.longestCommonPrefix1(array2));assertEquals("", obj.longestCommonPrefix2(array2));assertEquals("", obj.longestCommonPrefix3(array2));}
}