[LeetCode]14. Longest Common Prefix

水题

Posted by JinFei on February 12, 2020

题目描述

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 “”.

Example1:

Input: [“flower”,”flow”,”flight”]
Output: “fl”

Example1:

Input: [“dog”,”racecar”,”car”]
Output: “”
Explanation: There is no common prefix among the input strings.

解题思路

  • 水题
  • 两重循环,从第0个字符串的第0个字符开始,检查其他第1个字符串的第i位置是否相等
  • 如果不等,直接返回即可
  • 如果相等,继续循环。
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.size() == 0){
            return "";
        }
        int maxLen = 0;
        char c = strs[0][maxLen];
        int i, j;
        for(i = 0; i < strs[0].size(); i++){
            char c = strs[0][i];
            for(j = 1; j < strs.size(); j++){
                if(strs[j][i] != c){
                    return strs[0].substr(0, i);
                }
            }
        }
        return strs[0].substr(0, i);
    }
};