设为首页 加入收藏

TOP

leetcode笔记:Longest Common Prefix
2016-01-29 16:31:24 】 浏览:163
Tags:leetcode 笔记 Longest Common Prefix

一. 题目描述

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

二. 题目分析

题目的大意是,给定一组字符串,找出所有字符串的最长公共前缀。

对比两个字符串的最长公共前缀,其前缀的长度肯定不会超过两个字符串中较短的长度,设最短的字符串长度为n,那么只要比较这两个字符串的前n个字符即可。

使用变量prefix保存两个字符串的最长公共前缀,再将prefix作为一个新的字符串与数组中的下一个字符串比较,以此类推。
一个特殊情况是,若数组中的某个字符串长度为0,或者求得的当前最长公共前缀的长度为0,就直接返回空字符串。

三. 示例代码

#include 
   
     #include 
    
      #include 
     
       using namespace std; class Solution { public: string longestCommonPrefix(vector
      
        &strs) { if (strs.size() == 0) return ; string prefix = strs[0]; for (int i = 1; i < strs.size(); ++i) { if (prefix.length() == 0 || strs[i].length() == 0) return ; int len = prefix.length() < strs[i].length()  prefix.length() : strs[i].length(); int j; for (j = 0; j < len; ++j) { if (prefix[j] != strs[i][j]) break; } prefix = prefix.substr(0,j); } return prefix; } };
      
     
    
   

四. 小结

该题思路不难,而且还有几种相似的解决思路,在实现时需要做到尽量减少比较字符的操作次数。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇poco c++框架:本质概述 下一篇C++入门学习――虚函数表介绍

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目