//编写一个函数来查找字符串数组中的最长公共前缀。 
//
// 如果不存在公共前缀,返回空字符串 ""。 
//
// 
//
// 示例 1: 
//
// 
//输入:strs = ["flower","flow","flight"]
//输出:"fl"
// 
//
// 示例 2: 
//
// 
//输入:strs = ["dog","racecar","car"]
//输出:""
//解释:输入不存在公共前缀。 
//
// 
//
// 提示: 
//
// 
// 0 <= strs.length <= 200 
// 0 <= strs[i].length <= 200 
// strs[i] 仅由小写英文字母组成 
// 
// Related Topics 字符串 
// 👍 1462 👎 0

/*
* 14 最长公共前缀
* 2021-02-19 23:04:38
* @author oxygenbytes
*/ 
#include "leetcode.h" 
//leetcode submit region begin(Prohibit modification and deletion)

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.empty()) return "";

        string prefix = strs[0];

        for(int i = 1;i < strs.size();i++){
            int k = 0;
            while(k < min(strs[i].length(), prefix.length())){
                if(strs[i][k] != prefix[k]){
                    break;
                }
                k++;
            }
            prefix = prefix.substr(0, k);
        }
        return prefix;

    }
};

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = strs.size();

        if(n == 0) 
          return "";

        size_t m = strs[0].length();

        for(int i = 1;i < n;i++){
          m = min(m, strs[i].length());
        }

        for(int s = 1;s <= m;s++){
          char c = strs[0][s-1];
          for(int i = 1;i < n;i++){ // start from s == 1
            if(strs[i][s-1] != c) // if not match , then get the result
              return strs[0].substr(0, s-1);
          }
        }

        return strs[0].substr(0, m);
    }
};
//leetcode submit region end(Prohibit modification and deletion)