Tuesday, March 31, 2015

LeetCode [14] Longest Common Prefix

 14. Longest Common Prefix

Easy

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

If there is no common prefix, return an empty string "".

 

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

 

Constraints:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        int n = strs.size();
        if(n==0) return "";

        for(int index = 0; ;index++){
            if(strs[0].size()==index) return strs[0].substr(0,index);
            int c = strs[0][index];
            for(int i=1; i<n; ++i){
                if(strs[i].size()==index) return strs[0].substr(0,index);
                if(c!=strs[i][index]) return strs[0].substr(0,index);
            }
        }
        return strs[0];
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string ret = "";
        int n = strs.size();
        if(!n) return ret;

        int index = 0;
        while(true){
            if(index>=strs[0].size()) return ret;
            char c = strs[0][index];
            for(int i=1; i<n; ++i){
                if(index>=strs[i].size() || c!=strs[i][index]) return ret;
            }
            ret += c;
            index++;
        }
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public String longestCommonPrefix(String[] strs) {
        String r = "";
        if(strs.length==0) return r;
        int index = 0;
        while(true){
            char c = '.';
            for(String s : strs){
                if(index==s.length()) return r;
                else if(c!='.' && c!=s.charAt(index)) return r;
                else{
                    c = s.charAt(index);
                }
            }
            index++;
            r += c;
        }
    }
}

No comments:

Post a Comment