leetcode22: longest common prefix
来源:互联网 发布:立体匹配算法不是全局 编辑:程序博客网 时间:2024/04/28 01:57
class Solution: # @return a string def longestCommonPrefix(self, strs): ''' return a string which is the longest common prefix. >>> ['afdf', 'af', 'asfdadf'] 'af' ''' if len(strs)<1: return '' com = '' for i in range(0, len(strs[0])): c = strs[0][i] for str in strs[1:]: if len(str) <= i or str[i]!=c: return com #end for com += c #end for return com
Write a function to find the longest common prefix string amongst an array of strings.
reminders: 1.
class Solution {public: string longestCommonPrefix(vector<string> &strs) { // Start typing your C/C++ solution below // DO NOT write int main() function // in this question, common prefix means continuious predix substring which is different from the common substring in CLRS. // remember this, comfirm it with interviwer before starting to solve problem. if( strs.size() ==0) return ""; if( strs.size() < 2) return strs[0]; //if( strs[0].size() == 0 ) return ""; this statement is useless, because if the size equeals to 0, it won't go into loop. char c; string rel; for( int i=0; i<strs[0].size(); i++) { c = strs[0][i]; for( int j=1; j<strs.size(); j++) { if( strs[j][i] != c || strs[j].size() <= i ) { return rel; } } rel.push_back( c ); } return rel; }};
public class Solution { public String longestCommonPrefix(String[] strs) { // Start typing your Java solution below // DO NOT write main() function //check input // "a,b,c" "a,b" "a,b,c,d" if(strs==null || strs.length < 1) return ""; for(int i=0; i<strs[0].length(); i++) { char c = strs[0].charAt(i); for(int j=1; j<strs.length; j++) { if(i>=strs[j].length() || c != strs[j].charAt(i) ) { return strs[0].substring(0,i); } } } return strs[0]; }}
- leetcode22: longest common prefix
- LeetCode: Longest Common Prefix
- LeetCode Longest Common Prefix
- LeetCode : Longest Common Prefix
- [Leetcode] Longest Common Prefix
- leetcode6: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
- 星巴克不使用两阶段提交
- leetcode21: Integer to Roman
- leetcode 21: Length of Last Word
- 窥探小说类网站seo
- 对生物毒性的理解
- leetcode22: longest common prefix
- css设置中文字体
- leetcode 23: Longest Substring Without Repeating Characters
- BASH中的特殊符号
- C++Primer再读读书笔记:第一、二章
- 370. Reading is to the mind while exercise is to the body. 读书健脑,运动健身
- 罗德斯瓦茨功率计Windows ICE远程调用安装
- Yii Framework 开发教程(47) 主题 Theme 示例
- 笑话