编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
- 当输入为空时,不存在
strs[0]
,因此,输入为空时需单独讨论- 最长公共前缀长度不大于strs中最短的字符串长度
(1)C++
class Solution { public: string longestCommonPrefix(vector<string>& strs){ int n = strs.size(); if(n==0) return ""; string s = ""; string temp = strs[0]; for(int i =1; i<n; i++){ if(temp.length()<strs[i].length()) temp = strs[i]; } for(int j=0;j<temp.size();j++){ char temp = strs[0][j]; bool flag = true; for(int i=1; i<n ;i++){ if(temp != strs[i][j]) flag = false; } if(flag) s+=temp; else break; } return s; } };
(2)C++(C++中无数组字符串的边界检测)
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(strs.size() == 0) return ""; string s = strs[0]; for(int i = 1; i < strs.size(); i++) { for(int j = 0; j < s.length(); j++) { if(s[j] != strs[i][j]) { s = s.substr(0, j); break; } } } return s; } };
(3)python
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if(len(strs)==0): return "" res = strs[0] for each in strs: if len(res)>len(each): res = each for i in range(len(strs)): for j in range(len(res)): if res[j]!= strs[i][j]: res = res[:j] break return res