Leetcode #14. Longest Common Prefix

来源:互联网 发布:sd卡数据恢复软件 编辑:程序博客网 时间:2024/06/05 10:44

原题:

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

思路:

普通的字符串处理题,可以直接通过逐位的循环来检测;可以通过先找出最短字符串的预处理来优化匹配过程。


代码:

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        if(!strs.size())            return "";        int minLen = INT_MAX;        string _std;        for(int i(0); i < strs.size(); i++)        {            if(minLen > strs[i].length())            {                _std = strs[i];                minLen = strs[i].length();            }        }        bool flag = 1;        int pos;        for(pos = 0; pos < _std.length(); pos++)        {            for(int j(0); j < strs.size(); j++)            {                if(_std[pos] != strs[j][pos])                {                    flag = 0;                    break;                }            }            if(!flag)            {                pos --;                break;            }        }        string ans = "";        for(int i(0); i <= pos; i++)           ans += _std[i];        return ans;    }};