LeetCode: Longest Common Prefix

来源:互联网 发布:yum 安装jdk 编辑:程序博客网 时间:2024/06/05 23:22

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

For example:

  1. {"a","a","b"} should give "" as there is nothing common in all the 3 strings.

  2. {"a", "a"} should give "a" as a is longest common prefix in all the strings.

  3. {"abca", "abc"} as abc

  4. {"ac", "ac", "a", "a"} as a.

我的代码:

string longestCommonPrefix(vector<string>& strs) {
        
        if (strs.empty())
            return "";
        int s = strs.size();
        string first = strs[0];
        int j = 0;
        int i;
        char c;
        char m;
        string result = "";
        while(first[j] != '\0'){
            c = first[j];
            for(i = 1; i < s; i++){
               if(strs[i].size() <= j){
                   break;
                }
                m = strs[i][j];
                if(m != c && j == 0){
                    return result;
                }
                if(m != c)
                    break;
            }
           
            if(i == s){
                result = result + c;
                
            }
                
            j++;
        }
        return result;


大概思路就是把每一个string的每一个字符一个个比较。如果用java写的话会简单一点,java的string有indexof()的函数,可以先找到第一个和第二个string的最长prefix,然后用indexof函数找后面其他string最长与prefix相同的prefix。

      

public String longestCommonPrefix(String[] strs) {    if (strs.length == 0) return "";    String prefix = strs[0];    for (int i = 1; i < strs.length; i++)        while (strs[i].indexOf(prefix) != 0) {            prefix = prefix.substring(0, prefix.length() - 1);            if (prefix.isEmpty()) return "";        }            return prefix;}

原创粉丝点击