博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Find substring with K-1 distinct characters
阅读量:6157 次
发布时间:2019-06-21

本文共 2469 字,大约阅读时间需要 8 分钟。

参考 

Find substring with K distinct characters(http://www.cnblogs.com/pegasus923/p/8444653.html)

Given a string and number K, find the substrings of size K with K-1 distinct characters. If no, output empty list. Remember to emit the duplicate substrings, i.e. if the substring repeated twice, only output once.

  • 字符串中等题。Sliding window algorithm + Hash。此题跟上题的区别在于,子串中有一个重复字符。
  • 思路还是跟上题一样,只是需要把对count的判断条件改成dupCount。当窗口size为K时,如果重复字符只有一个的话,则为结果集。对dupCount操作的判断条件,也需要改为>0, >1。
1 // 2 //  main.cpp 3 //  LeetCode 4 // 5 //  Created by Hao on 2017/3/16. 6 //  Copyright © 2017年 Hao. All rights reserved. 7 // 8  9 #include 
10 #include
11 #include
12 using namespace std;13 14 class Solution {15 public:16 vector
subStringK1Dist(string S, int K) {17 vector
vResult;18 19 // corner case20 if (S.empty()) return vResult;21 22 unordered_map
hash;23 24 // window start/end pointer, hit count25 int left = 0, right = 0, dupCount = 0;26 27 while (right < S.size()) {28 if (hash[S.at(right)] > 0) // hit the condition dup char29 ++ dupCount;30 31 ++ hash[S.at(right)]; // count the occurrence32 33 ++ right; // move window end pointer rightward34 35 // window size reaches K36 if (right - left == K) {37 if (1 == dupCount) { // find 1 dup char38 if (find(vResult.begin(), vResult.end(), S.substr(left, K)) == vResult.end()) // using STL find() to avoid dup39 vResult.push_back(S.substr(left, K));40 }41 42 // dupCount is only increased when hash[i] > 0, so only hash[i] > 1 means that dupCount was increased.43 if (hash[S.at(left)] > 1)44 -- dupCount;45 46 -- hash[S.at(left)]; // decrease to restore occurrence47 48 ++ left; // move window start pointer rightward49 }50 }51 52 return vResult;53 }54 };55 56 int main(int argc, char* argv[])57 {58 Solution testSolution;59 60 vector
sInputs = { "aaabbcccc","awaglknagawunagwkwagl", "abccdef", "", "aaaaaaa", "ababab"};61 vector
iInputs = { 4, 4, 2, 1, 2, 3};62 vector
result;63 64 /*65 {abbc }66 {awag naga agaw gwkw wkwa }67 {cc }68 {}69 {aa }70 {aba bab }71 */72 for (auto i = 0; i < sInputs.size(); ++ i) {73 result = testSolution.subStringK1Dist(sInputs[i], iInputs[i]);74 75 cout << "{ ";76 for (auto it : result)77 cout << it << " ";78 cout << "}" << endl;79 }80 81 return 0;82 }
View Code

 

转载于:https://www.cnblogs.com/pegasus923/p/8444985.html

你可能感兴趣的文章
html / css学习笔记-1
查看>>
[学习笔记]标记永久化
查看>>
Android把自己应用加入到系统文件分享中
查看>>
SQL Server安装计划
查看>>
写在山理工之行之后。
查看>>
检查DISPLAY设置时Xlib出现No protocol specified错误
查看>>
如何使用Photoshop制作真实的尺子
查看>>
linux 再多的running也挡不住锁
查看>>
算法笔记--字符串hash
查看>>
strak组件(9):关键字搜索
查看>>
ReactNative 常见红屏黄屏及终端报错
查看>>
[xsy3343]程序锁
查看>>
线性模型(1) —— 多元线性回归
查看>>
PHP函数——urlencode() 函数
查看>>
Net性能分析与调试培训资料
查看>>
VB.NET 开发ColorPicker例子
查看>>
按照指定字符(@split )分割字符串,并取第@index 个
查看>>
Android判断当前线程是否是主线程的方法
查看>>
DBA日常工作内容和职责
查看>>
【Python爬虫学习实践】基于BeautifulSoup的网站解析及数据可视化
查看>>