LeetCode 14 最长公共前缀
题目:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
思路
1.如果字符串数组为空,返回空
2.任取字符串数组中一个字符串,从长到短取自身前缀去和数组其他字符串比较
3.如果某个前缀同时也是其他字符串前缀则此前缀为最长公共前缀
图解:
例: strs = ["flower","flow","flight"]
我们取第一个字符串"flower"作为比较对象
| 字符串/前缀 | flower | flowe | flow | flo | fl |
| flower | ✅ | ✅ | ✅ | ✅ | ✅ |
| flow | ❌ | ❌ | ❌ | ✅ | ✅ |
| flight | ❌ | ❌ | ❌ | ❌ | ✅ |
返回结果 "fl" 即可
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
| public String longestCommonPrefix(String[] strs) { String result = ""; if (strs.length == 0) return result; result = strs[0]; for (int i = 1; i < strs.length; i++) { int n = result.length(); while (!strs[i].startsWith(result)) { result = result.substring(0, --n); } if (result.length() == 0) break; } return result; }
|