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];    }}