LeetCode: Longest Common Prefix

14. Longest Common Prefix

 
Total Accepted: 91715 Total Submissions: 330844 Difficulty: Easy

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

 

    依次比较每个字符串的第j个字母,当出现一个不同的即退出。注意:字符串数组为空或者大小为1的情况该如何处理。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = strs.size();
        string res = "";
        if(n==0)
            return res;
        else if(n==1)
            return strs[0];
        bool flag = false;
        int j = 0;
        while (true)
        {
            char tmp = strs[0][j];
            for (int i = 1; i < n; i++)
            {
                if (strs[i][j] != tmp ||!strs[i][j])
                {
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
            else
            {
                res = res + tmp;
                j++;
            }
        }
        return res;
    }
};

 

posted @ 2016-03-21 16:42  翎飞蝶舞  阅读(164)  评论(0编辑  收藏  举报