zoukankan      html  css  js  c++  java
  • [LeetCode] #14 Longest Common Prefix

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

     本题寻找一组字符串的公共前缀,只需要查询较短子串前n个字符是否相等。时间:8ms

    代码如下:

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if (strs.size() == 0)
                return "";
            string str = strs[0];
            for (int i = 1; i < strs.size(); i++){
                if (strs[i].size() == 0 || str.size() == 0)
                    return "";
                int n = (str.size()<strs[i].size() ?str.size():strs[i].size());
                int j = 0;
                for (; j < n; j++){
                    if (str[j] != strs[i][j])
                        break;
                };
                str = str.substr(0, j);
            }
            return str;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    DockerAPI版本不匹配的问题
    Linux文件系统
    队列

    多维数组
    字符串
    线性表
    ARM编辑、编译工具
    南京IT公司
    数据结构:用单链表实现的队列(2)
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4440228.html
Copyright © 2011-2022 走看看