LeetCode Longest Common Prefix

来源:互联网 发布:思科arp绑定mac地址 编辑:程序博客网 时间:2024/06/06 00:33

题目:

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

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


0 0
原创粉丝点击