LeetCode9.Array and String — Longest Common Prefix 最长共同前缀

Posted hu-19941213

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode9.Array and String — 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:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

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.

存储string类型的向量一定程度上可以看成二维数组。 最重要的思想是按照最小长度的字符串作为最外层遍历循环。

class Solution 
public:
string longestCommonPrefix(vector<string>& strs)

    //首先,找到所有字符串中最短的那一个.
    int min=0;
    for (int i = 0; i < strs.size(); i++)
    
        if (min < strs[i].size()) min = strs[i].size();
    
    if (min == 0) return "" ;
    //然后根据最短的那个字符串进行遍历
    string result="" ;
    int counter = 0;//计数器
    for (int i = 0; i < min; i++)
    
        char compare = strs[0][i];
        for (int j = 0; j < strs.size(); j++)
        
            if (strs[j][i] == compare) 
                continue;
            
            else return result;
        
        result.push_back(compare);
    
    return result;

;

 

以上是关于LeetCode9.Array and String — Longest Common Prefix 最长共同前缀的主要内容,如果未能解决你的问题,请参考以下文章

[TypeScript] Interface and Class

UVa 1643 Angle and Squares (计算几何)

Java String, StringBuilder, StringBuffer

错误:没有匹配的功能?

Strin类

first-unique-character-in-a-string