LeetCode14-Longest Common Prefix(C++)

Description

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.

AC代码

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string res = "";
        if((strs.size() == 0) || (strs[0].size() == 0)){
            return res;
        }

        if(strs.size() == 1) {
            return strs[0];
        }

        string temp = strs[0];

        for(int i=0; i<strs[0].size(); i++) {
            for(int j=1; j<strs.size(); j++) {
                if(strs[j][i] != strs[0][i]) {
                    return res;
                }
            }
            res += strs[0][i];
        }

        return res;
    }
};

测试代码

int main() {
    Solution s;
    vector<string> a1{"flower", "flow", "flight"};
    vector<string> a2{"dog", "racecar", "car"};

    cout << "prefix of a1 is " << s.longestCommonPrefix(a1) << endl;
    cout << "prefix of a2 is " << s.longestCommonPrefix(a2) << endl;
}

总结

这一题比较简单,做完边界条件的判定之后,两层for循环,一旦条件不满足,立马return。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 3,236评论 0 3
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,950评论 0 13
  • 函数调用 Built-in Functions abs(x) Return the absolute value ...
    叫我七夜阅读 1,323评论 0 0
  • 贾平凹(wa)的独行世界,写给每个孤独的行路人。 作者简介~ 我国当代文坛声名显赫的文学大师,一位极具叛逆性的作家...
    Laughing_5311阅读 648评论 0 0
  • 咋们书接上回,上个作品咱们说到要去顺峰山公园看灯光展。今天我们一家就去了顺峰山公园。在车上的时候,爸妈还晕车呢...
    杨阳_f5ad阅读 216评论 0 1

友情链接更多精彩内容