LeetCodet题解--14. Longest Common Prefix

链接


LeetCode题目:https://leetcode.com/problems/longest-common-prefix/

GitHub代码:https://github.com/gatieme/LeetCode/tree/master/014-LongestCommonPrefix

CSDN题解:http://blog.csdn.net/gatieme/article/details/51055968

题意


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

找出所有字符串的最长公共前缀。这道题很简单,但需要注意减少比较字符的操作次数。

解法


思路:设置一个位数记录器num,遍历所有字符串的第num位。如果都相同,则num++。

直到某字符串结束或者所有字符串的第num位不都相同,则返回[0~num-1]位,即最长公共前缀。

时间复杂度:O(nm)(n是字符串数组长度,m是字符串长度)

空间复杂度:O(1)

#include <iostream>
#include <string>
#include <vector>

using namespace std;

#define __tmain main

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs)
    {
        string result = "";
        bool flag = false;
        if(strs.size( ) == 0)
        {
            return "";
        }
        else if(strs.size( ) == 1)
        {
            return strs[0];
        }

        // 每次第1个字符串的pos位为基准
        for(int pos = 0; pos < strs[0].size(); pos++)
        {
            char temp = strs[0][pos];
            for(int index = 1; index < strs.size(); index++)
            {
                if(strs[index][pos] != temp)
                {
                    flag = true;
                    break;
                }
            }
            if(flag == true)
            {
                break;
            }
            result += strs[0][pos];
        }
        return result;
    }
};
int __tmain( )
{
    string str[2] = {"a", "b"};
    vector<string> strs(str, str + 2);

    Solution solu;
    cout <<solu.longestCommonPrefix(strs) <<std::endl;

    return EXIT_SUCCESS;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值