1. 程式人生 > >【LeetCode】14. Longest Common Prefix

【LeetCode】14. Longest Common Prefix

1. 題目描述:

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: [“flower”,“flow”,“flight”]
Output: “fl”

Example 2:

Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.

Note:
All given inputs are in lowercase letters a-z.

2. 思路分析:

題目的意思是給定一個字串陣列,找到陣列中所有字串最長的公共字首。

最簡單的思路就是將str[0],當作當前最長公共字首,然後依次遍歷後續的字串,如果含有當前公共字首,則繼續遍歷;如果不含當前公共字首,則將當前公共字首去掉最後一個字元,再繼續比較;最後剩下的當前公共字首即是所有字串的公共字首。

3. Java程式碼:

程式碼:

public static String longestCommonPrefix(String[] strs) {
    if (strs.length ==
0) { return ""; } String curPrefix = strs[0]; for (int i = 1; i < strs.length; i++) { while (strs[i].indexOf(curPrefix) != 0) { curPrefix = curPrefix.substring(0, curPrefix.length() - 1); if (curPrefix.isEmpty()) { return ""; }
} } return curPrefix; }