[LeetCode 14] Longest Common Prefix


[Problem Link]

Description

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

Input: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

Solution

思路:判斷所有字符串的每一位是否相同,若相同添加進返回字符串,否則結束循環。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string ans = "";
        int stringNum = strs.size();
        if (stringNum == 0) return "";
        int minLen = strs[0].length();
        for (int i = 0; i < stringNum; i++) {
            int length = strs[i].length();
            minLen = min(minLen, length);
        }
        if (minLen == 0) return ""; 
        for (int j = 0; j < minLen; j++) {
            char temp = strs[0][j];
            for(int i = 0; i < stringNum; i++) {
                if(strs[i][j] != temp) {
                    return ans;
                }
            }
            ans = ans + strs[0][j];
        }
        return ans;
    }
};

Summary

  • string::length的返回值類型爲size_t,size_t is an unsigned integral type (the same as member type string::size_type).
  • min(a, b)中a和b必須同爲有符號數或無符號數。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章