当前位置: 首页 > news >正文

数据结构与算法:Find All Anagrams in a String

给出两个字符串s和p,当s中存在p的异构串时,返回所有s中对应的所有起点位置。

Example 1:

Input: s="cbaebabacd", p="abc"Output:[0,6]Explanation: The substring with start index=0is"cba",whichis an anagram of"abc".The substring with start index=6is"bac",whichis an anagram of"abc".

Example 2:

Input: s="abab", p="ab"Output:[0,1,2]Explanation: The substring with start index=0is"ab",whichis an anagram of"ab".The substring with start index=1is"ba",whichis an anagram of"ab".The substring with start index=2is"ab",whichis an anagram of"ab"
importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;publicclassCode_FindAllAnagramsInAString{publicstaticList<Integer>findAnagrams(Strings,Stringp){List<Integer>ans=newArrayList<>();char[]str=s.toCharArray();char[]ptr=p.toCharArray();intM=p.length();Map<Character,Integer>map=newHashMap<>();intall=M;intN=str.length;if(M>N){returnans;}for(inti=0;i<M;i++){if(map.containsKey(ptr[i])){map.put(ptr[i],map.get(ptr[i])+1);}else{map.put(ptr[i],1);}}for(intend=0;end<M-1;end++){if(map.containsKey(str[end])){intcount=map.get(str[end]);if(count>0){all--;}map.put(str[end],count-1);}}// map表相当于一张欠表。 别人欠我多少。// 比如p字符串 abc. 那么map的数据是 a,1; b,1; c,1; 别人欠我1个// a, 欠1个b,欠1个c. all变量表示一共欠多少。for(intend=M-1,start=0;end<N;end++,start++){if(map.containsKey(str[end])){intcount=map.get(str[end]);if(count>0){all--;}map.put(str[end],count-1);}if(all==0){ans.add(start);}if(map.containsKey(str[start])){intcount=map.get(str[start]);if(count>=0){all++;}map.put(str[start],count+1);}}returnans;}}
http://www.jsqmd.com/news/364850/

相关文章:

  • 在 wsl 中安装 opencode
  • 2026年2月GEO公司哪家好?GEO服务商TOP9综合实力权威排行榜 - 资讯焦点
  • 护理床哪个牌子好?2026年最新品牌排行榜出炉 - 资讯焦点
  • 导师又让重写?AI论文平台 千笔AI VS PaperRed,本科生写作神器!
  • 小蓝翼家庭中央空调怎么样?TCL 空调引领行业技术发展 - 资讯焦点
  • GEO生成式引擎优化获国家级认可GEO理论创始人罗小军荣膺优秀作者 - 资讯焦点
  • 2026年全球GEO优化头部公司综合实力TOP 7权威榜单深度指南 - 资讯焦点
  • 苏果超市卡回收方法解析 - 资讯焦点
  • 手把手教你京东e卡回收变现,轻松搞定闲置卡 - 团团收购物卡回收
  • 2026年广东学校直饮水/校园饮水机/医院净水设备/办公室净水器口碑品牌综合评估报告 - 2026年企业推荐榜
  • 钢丝上的智能突围:企业AI创新与安全的动态平衡之道(2024-2026前瞻版)
  • 面向对象程序设计TODO
  • 当 MrBeast 遇上 Whatnot:揭秘超级碗背后的亿级流量支撑
  • 2026国产工业CT检测系统TOP10企业评测全解析 - 资讯焦点
  • 2026高口碑推荐:GMPC认证沐浴用品专业生产厂家 - 资讯焦点
  • 声网兄弟品牌 Agora:如何搞定 MrBeast 的超级碗级挑战?
  • 2026年护理床行业格局巨变:5大前沿品牌技术路线深度拆解 - 资讯焦点
  • 京东e卡回收变现全攻略:让闲置卡片秒变现金 - 团团收购物卡回收
  • 2026深圳儿童近视防控新标准:从南山到福田,为何数智化配镜成了刚需? - 资讯焦点
  • 京东e卡回收变现流程详解,用最快方式赚现金 - 团团收购物卡回收
  • 上海如何挑选自助仓库?三大关键点助你避坑
  • 卖掉你的京东e卡:从回收到变现的一站式解决方案 - 团团收购物卡回收
  • 韩国爱豆们的冬季随身好物 艾草蒸敷贴持续温热陪伴
  • 2026少儿编程品牌哪家强?十大品牌综合实力榜权威发布! - 匠言榜单
  • 2026年工业 MCU 哪家好?深度测评十大厂商综合实力 - 资讯焦点
  • 坚守与赋能:态度个性的当代诠释及AI大模型智能名片小程序的实践赋能
  • 2026年球场围网优质厂家推荐指南 - 资讯焦点
  • 内网 NAS 也能远程管?Ansible+cpolar 解锁便捷运维新方式
  • AI测试AI:递归测试框架的构建
  • YOLO26原创自研:低对比度场景 | 平滑的 CIoU,对其惩罚项(中心点距离和长宽比差异)进行平滑