Longest Common Prefix Problem


Description

LeetCode Problem 14.

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:

1
2
Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

1
2
3
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.size() == 0)
            return "";
        string prefix = strs[0];
        int p = strs[0].size();
        int i, j;
        for (i = 0; i < strs.size(); i ++) {
            for (j = 0; j < p; j ++) {
                if (prefix[j] != strs[i][j])
                    break;
            }
            p = j;
            prefix = prefix.substr(0, p);
        }
        return prefix;
    }
};




Related Posts

Valid Number Problem

LeetCode 65. Given a string s, return true if s...

Text Justification Problem

LeetCode 68. Given an array of strings words and a...

Valid Number Problem

LeetCode 67. A robot is located at the top-left corner...

Length Of Last Word Problem

LeetCode 58. Given a string s consisting of some words...

Zigzag Conversion Problem

LeetCode 6. Write the code that will take a string...

Wildcard Matching Problem

LeetCode 44. Write the code that will take a string...