zoukankan      html  css  js  c++  java
  • 【LeetCode】LeetCode——第14题:Longest Common Prefix

    14. Longest Common Prefix

       My Submissions
    Total Accepted: 97052 Total Submissions: 345681 Difficulty: Easy

    Write a function to find the longest common prefix string amongst an array of strings.

    Subscribe to see which companies asked this question

    Show Tags










    题目的大概意思是:输入多个字符串,找到它们的最长公共前缀。

    这道题难度等级:简单

    说明:如:“abcd”、“abefh”、“absyz”则其最长公共前缀为"ab";再如:“abcdefg”、“abcfg”、“gabcdest”则其最长公共前缀为空。通过举例说明可知,这里的最长公共前缀指的是从每一个字符串的第一个位置開始。若都同样,则匹配下一个。直到出现一个不同样或者某个字符串完结为止。

    了解了题意之后。代码例如以下:

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
    		if (strs.empty()){return "";}
    		for (unsigned int i = 0; i < strs[0].length(); ++i){
    			for (unsigned int j = 1; j < strs.size(); ++j){
    				if ((i >= strs[j].length()) || (strs[0][i] != strs[j][i])){
    					return i > 0 ? strs[0].substr(0, i) : "";
    				}
    			}
    		}
    		return strs[0];
        }
    };
    提交代码后。顺利AC,Runtime: 4 ms

  • 相关阅读:
    poj 1700 Crossing River 过河问题。贪心
    Alice's Print Service
    POI 2000 ------Stripes
    Uva 1378
    hdu 3068 最长回文
    bnu Game 博弈。
    链栈的C语言实现
    链栈的C语言实现
    顺序栈C语言实现
    顺序栈C语言实现
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7260354.html
Copyright © 2011-2022 走看看