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

    原题链接:http://oj.leetcode.com/problems/longest-common-prefix/

    题目描述:

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

    题解:

      依然是一道分治法解的题,类似的还有http://www.cnblogs.com/codershell/p/3592992.html

     1 class Solution {
     2 public:
     3     string lcp(string str1,string str2){
     4         int len1 = str1.length();
     5         int len2 = str2.length();
     6         int i,j;
     7         for(i=0,j=0; i<len1&&j<len2; i++,j++){
     8             if(str1[i] != str2[j] )
     9                 break;
    10         }
    11         return str1.substr(0,i);
    12     }
    13     string longestCommonPrefix(vector<string> &strs) {
    14         int size = strs.size();
    15         if(size == 0)
    16             return "";
    17         if(size == 1)
    18             return strs[0];
    19         vector<string> A,B;
    20         for(int i=0; i<size/2; i++){
    21             A.push_back(strs[i]);
    22         }
    23         for(int i=size/2; i<size; i++){
    24             B.push_back(strs[i]);
    25         }
    26         return lcp(longestCommonPrefix(A),longestCommonPrefix(B));
    27     }
    28 };
    View Code
  • 相关阅读:
    实验任务四
    java语言基础第二讲 课程作业02 总结
    java 计算精度处理
    构建之法阅读笔记02
    周活动总结表
    周进度条
    构建之法阅读笔记01
    四则运算软件需求规格说明书
    四则运算2
    周进度条
  • 原文地址:https://www.cnblogs.com/codershell/p/3594787.html
Copyright © 2011-2022 走看看