LeetCode OJ 14 Longest Common Prefix

来源:互联网 发布:js 数组 empty 编辑:程序博客网 时间:2024/06/04 08:05

题目:

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

难度:

Easy

思路: 从头开始比较每个字符串,不等就停止循环即可

代码如下

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        if(strs.empty())            return "";        for(int i=0;i<strs[0].length();i++)            for(int j=0;j<strs.size();j++){                if(i>=strs[0].length()||strs[0][i]!=strs[j][i])                    return strs[0].substr(0,i);            }        return strs[0];    }};


0 0
原创粉丝点击