zoukankan      html  css  js  c++  java
  • [CTCI] 子串判断

    子串判断

    题目描述

    现有一个小写英文字母组成的字符串s和一个包含较短小写英文字符串的数组p,请设计一个高效算法,对于p中的每一个较短字符串,判断其是否为s的子串。

    给定一个string数组p和它的大小n,同时给定string s,为母串,请返回一个bool数组,每个元素代表p中的对应字符串是否为s的子串。保证p中的串长度小于等于8,且p中的串的个数小于等于500,同时保证s的长度小于等于1000。

    测试样例:
    ["a","b","c","d"],4,"abc"
    返回:[true,true,true,false]


    后缀数组?二分查找!

     1 class Substr {
     2 public:
     3     bool matched(string a, string b) {
     4         if (b.length() < a.length()) return false;
     5         for (int i = 0; i < a.length(); ++i) if (a[i] != b[i]) return false;
     6         return true;
     7     }
     8     vector<bool> chkSubStr(vector<string> p, int n, string s) {
     9         // write code here
    10         set<string> st;
    11         vector<bool> res;
    12         for (int i = 0; i < s.length(); ++i) {
    13             st.insert(s.substr(i));
    14         }
    15         for (int i = 0; i < n; ++i) {
    16             auto it = st.lower_bound(p[i]);
    17             if (it == st.end()) {
    18                 res.push_back(false);
    19             } else {
    20                 if (matched(p[i], *it)) res.push_back(true);
    21                 else res.push_back(false);
    22             }
    23         }
    24         return res;
    25     }
    26 };
  • 相关阅读:
    scroll
    "严格模式" use strict 详解
    thymeleaf 模板布局
    前端性能优化
    原生的强大DOM选择器querySelector
    thymeleaf 基本语法
    读书笔记JavaScript中的全局对象
    JavaScript中getBoundingClientRect()方法详解
    JavaScript 中的内存泄漏
    jsonp 跨域原理详解
  • 原文地址:https://www.cnblogs.com/easonliu/p/4690706.html
Copyright © 2011-2022 走看看