# LeetCode 14. 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. ``` ## 解題思維 抓第一個字串,跟下一個字串做字元比對 先比對出相同子字串的位置,否則做字串切割,直到找出相同的子字串 ## 圖解 ![](https://i.imgur.com/tt140TB.png) ## Java ``` public String longestCommonPrefix(String[] strs) { String prefix = strs[0]; for (int i = 1; i < strs.length; i++) while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length() - 1); if (prefix.isEmpty()) return ""; } return prefix; } ```