Skip to content
Rain Hu's Workspace
Go back

[Leetcode] 14. Longest Common Prefix

Rain Hu

14. Longest Common Prefix


一、題目

Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".

Example 1:

Example 2:

Constraints:

二、分析

三、解題

1. String

string longestCommonPrefix(vector<string>& strs) {
    string res = strs[0];
    for (int i = 1; i < strs.size(); i++) {
        int j = 0;
        for (; j < min(strs[i].length(), res.length()); j++) {
            if (strs[i][j] != res[j]) break;
        }
        res = res.substr(0, j);
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1888. Minimum Number of Flips to Make the Binary String Alternating
Next
[Leetcode] 13. Roman to Integer