[LeetCode14] Longest Common Prefix

来源:互联网 发布:mac五国循环重启 编辑:程序博客网 时间:2024/06/06 18:42

Write a function to find the longest common prefix string amongst an array of strings.

Analysis:

Scan from the first character, if it is same to all strings, then scan the second one until meet the different or null.

c++

string longestCommonPrefix(vector<string> &strs) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if (strs.empty()){return "";}        string str = strs[0];        int i;        for (i=0;i<str.size();i++){            bool fl=true;            for (int j=0;j<strs.size();j++){                if (strs[j][i]!=str[i]) {fl=false; break;}            }            if (fl==false){return str.substr(0,i);}        }        return str.substr(0,i);    }

java

public String longestCommonPrefix(String[] strs) {        if(strs.length == 0) return "";        boolean flag = true;for(int i=0;i<strs[0].length();i++){for(int j=0;j<strs.length;j++){if(i>=strs[j].length() || strs[0].charAt(i)!=strs[j].charAt(i)){flag = false;break;}}if(!flag) return strs[0].substring(0,i);}return strs[0];    }


0 0