LeetCoder 14. Longest Common Prefix

xiaoxiao2021-02-28  71

题意

n <script type="math/tex" id="MathJax-Element-4">n</script>个字符串的公共前缀

思路

解法一: 构建字典树,将字符串加入字典树之后,遍历节点查看节点权值得出 解法二: 直接字符串暴力,找出公共前缀

结果

Your runtime beats 9.93 % of cpp submissions.

代码

class Solution { public: string longestCommonPrefix(vector<string>& strs) { size_t cnt = strs.size(); if(cnt == 0) return ""; string ans = strs[0]; for(size_t i = 1; i < cnt ; i++){ string temp = ""; string locString = strs[i]; size_t len = locString.length(); for(size_t j = 0; j < len;j++){ if(locString[j] == ans[j]){ temp += ans[j]; } else{ break; } } ans = temp; } return ans; } };
转载请注明原文地址: https://www.6miu.com/read-52985.html

最新回复(0)