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

String Without Aaa Or Bbb Problem

LeetCode 984. Given two integers a and b, return any...

Shifting Letters Problem

LeetCode 848. You are given a string s of lowercase...

Positions Of Large Groups Problem

LeetCode 830. In a string sof lowercase letters, these letters...

Orderly Queue Problem

LeetCode 899. You are given a string s and an...

Number Of Lines To Write String Problem

LeetCode 806. You are given a string s of lowercase...

Masking Personal Information Problem

LeetCode 831. You are given a personal information string s,...