zoukankan      html  css  js  c++  java
  • [CTCI] 最长合成字符串

    最长合成字符串

    题目描述

    有一组单词,请编写一个程序,在数组中找出由数组中字符串组成的最长的串A,即A是由其它单词组成的(可重复)最长的单词。

    给定一个string数组str,同时给定数组的大小n。请返回最长单词的长度,保证题意所述的最长单词存在。

    测试样例:
    ["a","b","c","ab","bc","abc"],6
    返回:3

    递归&备忘录。

     1 class LongestString {
     2 public:
     3     bool canBuild(string &s, bool isOriginalWord, map<string, bool> &mp) {
     4         if (mp.find(s) != mp.end() && !isOriginalWord) return mp[s];
     5         for (int i = 1; i < s.length(); ++i) {
     6             string left = s.substr(0, i);
     7             string right = s.substr(i);
     8             if (mp.find(left) != mp.end() && mp[left] && canBuild(right, false, mp)) {
     9                 return true;
    10             }
    11         }
    12         mp[s] = false;
    13         return false;
    14     }
    15     int getLongest(vector<string> str, int n) {
    16         // write code here
    17         map<string, bool> mp;
    18         for (auto &s : str) mp[s] = true;
    19         sort(str.begin(), str.end(), [](const string &a, const string &b) {
    20             return a.length() > b.length();
    21         });
    22         for (auto &s : str) {
    23             if (canBuild(s, true, mp)) return s.length();
    24         }
    25         return 0;
    26     }
    27 };
  • 相关阅读:
    CLR
    Cocos2dx 3.12 在AndroidStudio上编译配置
    MFC 调试方法
    列表初始化
    类型转换
    Cocos2d-x 3.4在AndroidStudio上编译配置
    出发 Let's Go
    LumiSoft.Net邮件接收乱码问题解决
    百度地图经纬度转换JS版
    百度经纬度和google经纬度互转
  • 原文地址:https://www.cnblogs.com/easonliu/p/4743873.html
Copyright © 2011-2022 走看看