14-Longest Common Prefix

来源:互联网 发布:java文件下载实例 编辑:程序博客网 时间:2024/05/17 04:47

类别:string

题目描述

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

算法分析

两层for循环判断两两之间的相同前缀,然后取长度最小的相同前缀即为最小共同前缀。

代码实现

class Solution {public:    string commonBetwTwo(string str1, string str2) {        string result = "";        int n1 = str1.length();        int n2 = str2.length();        int n = n1 < n2 ? n1 : n2;        for (int i = 0; i < n; ++i) {            if (str1[i] != str2[i]) break;            result += str1[i];        }        return result;    }    string longestCommonPrefix(vector<string>& strs) {        int n = strs.size();        if (n == 0) return "";        if (n == 1) return strs[0];        string ans = "";        string temp = "";        for (int i = 0; i < n; ++i) {            for (int j = i + 1; j < n; ++j) {                temp = commonBetwTwo(strs[i], strs[j]);           //     cout << "i=" << i << ", j=" << j << ":" << temp << endl;                if (i == 0 && j == 1) {                    ans = temp;                    continue;                }                if (temp.length() < ans.length()) {                    ans = temp;                }            }        }        return ans;    }};

main.cpp

#include <iostream>#include <string>#include <vector>using namespace std;int main() {    vector<string> strs;    int n;    cin >> n;    string str;    for (int i = 0; i < n; ++i) {        cin >> str;        strs.push_back(str);    }    cout << longestCommonPrefix(strs) << endl;    return 0;}
原创粉丝点击