classSolution { public: stringlongestCommonPrefix(vector<string>& ss){ int n = ss.size(); if (!n) return""; string res; for (int i = 0;; ++i) { if (i >= ss[0].size()) { return ss[0]; } char c = ss[0][i]; for (int j = 0; j < n; ++j) { if (ss[j][i] != c) { return res; } } res += c; } return res; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution{ public String longestCommonPrefix(String[] ss){ int n = ss.length; if (n == 0) return""; StringBuilder res = new StringBuilder(); for (int i = 0;; ++i) { if (i >= ss[0].length()) return ss[0]; // 第一个字符串在所有串中最短 char c = ss[0].charAt(i); for (String s : ss) { if (i >= s.length() || s.charAt(i) != c) return res.toString(); } res.append(c); } } }