Write a function to find the longest common prefix string amongst an array of strings.code
遍歷按序逐個比較,直接了當。string
耗時:6msit
class Solution { public: string longestCommonPrefix(vector<string>& strs) { string cm; int cm_i = 0; int n = strs.size(); if (n == 0) return cm; if (n == 1) return strs[0]; while (true) { char label = strs[0][cm_i]; for (int s_i = 1; s_i < n; s_i++) { if (cm_i >= strs[s_i].length() || strs[s_i][cm_i] != label) return cm; } cm += label; cm_i++; } return cm; } };