Longest Common Prefix
来源:互联网 发布:面向对象的c编程 编辑:程序博客网 时间:2024/05/21 22:51
first iteration
class Solution {public: string longestCommonPrefix(vector<string> &strs) { string prefix; // empty string vector if (strs.empty()) { return prefix; } int idx=0; char c; while (true) { // get character to be compared from first string if (idx < strs[0].size()) { c = strs[0][idx]; } else { break; } // check if all strings has that character in the index // - break out if either out of length or not same bool same = true; for (int i = 1; i < strs.size(); i++) { if (idx >= strs[i].size() || strs[i][idx] != c) { same = false; break; } } // grow prefix if it is same otherwise, break out if (same) { prefix.push_back(c); } else { break; } idx++; } return prefix; }};
2nd iteration with a little refactor
class Solution {public: string longestCommonPrefix(vector<string> &strs) { string prefix; // empty string vector if (strs.empty()) { return prefix; } int len=0; while (true) { char var; int i = 0; for (; i < strs.size(); i++) { // get character to be compared from first string // could be '\0', but we break out as below if (i==0) { var = strs[0][len]; } // break out if run out of length or character comparision // failed if (len == strs[i].size() || strs[i][len] != var) { break; } } // this means compare with this character failed, break out // and return whatever we got for prefix // NOTE: use the fact we early break out from for-loop or not to // determine if we need continue the check if (i != strs.size()) { break; } // continue the checkfor longest common prefix prefix.push_back(var); len++; } return prefix; }};
0 0
- LeetCode: Longest Common Prefix
- LeetCode Longest Common Prefix
- LeetCode : Longest Common Prefix
- [Leetcode] Longest Common Prefix
- leetcode6:Longest Common Prefix
- leetcode22: longest common prefix
- [LeetCode] Longest Common Prefix
- Leetcode14: Longest Common Prefix
- Longest Common Prefix
- Longest Common Prefix
- Longest Common Prefix
- [LeetCode]Longest Common Prefix
- Longest Common Prefix
- LeetCode-Longest Common Prefix
- Longest Common Prefix
- [LeetCode] Longest Common Prefix
- Longest Common Prefix
- LeetCode - Longest Common Prefix
- Recover Binary Search Tree
- 我是一只蜘蛛精
- 我是一只蜘蛛精
- 如何用PHPExcel读取超大excel文件
- 我是一只蜘蛛精
- Longest Common Prefix
- dxp altium design 集成库 元件的 编辑
- OmniGraffle 中文 - 汉化 6.1版本汉化
- 2014-11-20 网页收藏
- http://www.fang99.com/know99/question.aspx?Id=0000076838
- 交通银行如何获取白金资格或好享贷
- 未来经济发展之路:通胀?滞涨?通缩?还是崩溃?
- 刚发快递,听到一圆通业务和一韵达业务聊天,说今天双11都没有什么气氛
- 8后辞职专职做期货(21.5万起————我的期货实盘