Skip to content

14. Longest Common Prefix

难度:Easy

刷题内容

原题连接

  • https://leetcode.com/problems/longest-common-prefix/

内容描述

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

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:

All given inputs are in lowercase letters a-z.

˼·1 **- ʱ�临�Ӷ�: O(n^2)*- �ռ临�Ӷ�: O(1)***

���ǰ׺�����Ӵ���ֻ�б内容描述Ӵ������������Ӵ����ɣ�����Ҫע����ܴ��ڿ��ַ���

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {            
        string temp;
        if(!strs.size() || !strs[0].length())
            return temp;
        int j = 0;
        while(1)
        {
            int i = 0;
            int ch = strs[0][j];
            for(;i < strs.size();++i)
                if(j >= strs[i].length() || strs[i][j] != ch)
                    break;
            if(i != strs.size())
                break;
            temp.push_back(strs[0][j++]);
        }
        return temp;
    }
};


回到顶部