首页 > 代码库 > 【leetcode】Longest Common Prefix

【leetcode】Longest Common Prefix

题目:

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

解析:求字符串数组中所有数组的最长公共前缀,重点考察细节和边界条件,比如:
[] :输入字符串数组为空,要判断if (strs .size() == 0) return "";
[""]: 字符串数组里面只有一个空字符串等情况等等

class Solution {
public:
    string longestCommonPrefix(vector <string> & strs) {
                 if (strs .size() == 0) return "";
                 string result;
                 int i, j;  // i表示第i个字符串,j表示字符串的第j个字符
                 for (j = 0; ; j++){
                     for (i = 0; i<strs .size(); i++){
                         if (j >= strs [i].length() || strs[i][j] != strs[0][j])
                              break;
                     }
                     if (i<strs .size()) break;
                     result += strs[0][j];
                }
                 return result;
    }
};


【leetcode】Longest Common Prefix