Leetcode-14. Longest Common Prefix
2016-01-08 11:20
351 查看
Problem Description:
Write a function to find the longest common prefix string amongst an array of strings.
Analysis:
It’s an easy problem. First pieces of code is regular solution.
I try to use Trie (prefix tree) to solve the problem. Notice that, Trie is very helpful in prefix matching problem.
Using Trie data structure:
Python code:
Write a function to find the longest common prefix string amongst an array of strings.
Analysis:
It’s an easy problem. First pieces of code is regular solution.
I try to use Trie (prefix tree) to solve the problem. Notice that, Trie is very helpful in prefix matching problem.
string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) return ""; string lcp = ""; int m = strs.size(), n = strs[0].size(); for (int i = 0; i < n; ++i){ for (int j = 1; j < m; ++j) if (strs[j][i] != strs[0][i] || strs[j].size() == i) return lcp; lcp += strs[0][i]; } return lcp; }
Using Trie data structure:
class TrieNode { public: TrieNode* next[52];//upper and lower case bool end_Word; // end of a word int sons; // numbers of children TrieNode() : end_Word(false), sons(0) // { for (int i = 0 ; i < 52; ++i) next[i] = NULL; } }; class Trie { public: TrieNode * root; Trie () { root = new TrieNode(); } void insert(string word) { TrieNode * p = root; for (char c : word) { if (c >= 'a') { if (p -> next[c - 'a'] == NULL) { p -> next[c - 'a'] = new TrieNode(); p -> sons ++; // } p = p -> next[c - 'a']; } else { if (p -> next[c - 'A' + 26] == NULL) { p -> next[c - 'A' + 26] = new TrieNode(); p -> sons ++; } p = p -> next[c - 'A' + 26]; } } p -> end_Word = true; } }; class Solution { public: string longestCommonPrefix(vector<string>& strs) { Trie T; for(auto str : strs) T.insert(str); return findPrefix(T); } private : string findPrefix(Trie& T) { TrieNode* p = T.root; string res = ""; int i = 0; while (p -> sons == 1 && !p -> end_Word) { for (i = 0; i < 52; ++i) { if (p -> next[i]) { if (i < 26) res += char('a' + i); else res += char('A' + i - 26); break; } } if (i == 52) break; p = p -> next[i]; } return res; } };
Python code:
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ sz, ret = zip(*strs), "" # zip('ABCD', 'xy') --> Ax By for c in sz: if len(set(c)) > 1: break ret += c[0] return ret
相关文章推荐
- Python Numpy数组保存
- 5-21 求特殊方程的正整数解
- 正则表达式
- HTTPS那些事(二)SSL证书
- mysql replace VS insert & update
- CentOS7下安装phpcmsV9时提示文件权限不可写
- 360广告转化分析上线
- linux 文件权限后面一个点的含义
- 异常
- JSR
- 【甘道夫】HBase开发环境搭建过程中可能遇到的异常:No FileSystem for scheme: hdfs
- 全球顶级专家为你解读:什么是真正的 DevOps?
- 数论 - 119. Magic Pairs
- 手机端页面需要用rem设置字体大小的js代码
- 定义数组或遍历数组并输出
- Android jar包里面有assets目录下有文件,APP的assets里面也有文件,如何读呢?
- sencha touch 学习(1)
- HTTPS那些事(一)HTTPS原理
- ShareSDK微信支付成功不调用onResp、openURL、handleOpenURL等方法
- JAVA线程锁lock下Condition高级使用-多个Condition的整合使用