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

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

    题目言简意赅,貌似也不难,暴力法用一个char *数组存放strs里每个元素的起始地址,然后循环,同时把所有指针向前移动,

    如果有其中有一个字符失配就算完成,写的时候出现一个bug就是在移动指针的时候没有判断是否超出了那个string的长度,导致莫名其妙的问题。

    string longestCommonPrefix(vector<string> &strs) {
        if (strs.size() == 0) return string();
        if (strs.size() == 1) return strs[0];
        char *ptrs[strs.size()];
        for (int i = 0; i < strs.size(); i++) {
            ptrs[i] = &(strs[i][0]);
        }
        
        bool failed = false;
        int bias = 0;
        int i;
        string res;
        while (!failed){
            for (i = 1; i < strs.size(); i++) {
                if ((bias >= strs[i].size() || bias >= strs[i-1].size()) || *(ptrs[i]+bias) != *(ptrs[i-1]+bias)){
                    failed = true;
                    break;
                }
            }
            if (!failed){
                res += strs[0][bias];
                bias++;
            }
        }
        
        return res;
    }
  • 相关阅读:
    技术学习之分析思想
    测试类的必要性
    Webstorm配置运行React Native
    React Native
    npm太慢, 淘宝npm镜像使用方法
    数据库设计那些事儿
    Linux 安装nodejs
    Java
    解决 vmware workstations 14 开启虚拟机黑屏
    编程与盖楼的思考
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4049596.html
Copyright © 2011-2022 走看看