标签:let input 嵌套循环 元素 ref nbsp string i++ 滑动
应用及优点:
1.可用于解决数组或者字符串的子元素问题。
2.用单循环代替了嵌套循环问题,时间复杂度低。
3.用双指针维护动态窗口。
相关算法题:
以“Find All Anagrams in a String”为例:
Given a string s and a non-empty string p, find all the start indices of p‘s anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.The order of output does not matter.
Example 1:
Input: s: "cbaebabacd" p: "abc" Output: [0, 6]
class Solution { public List<Integer> findAnagrams(String s, String p) { int [] need=new int[128]; int [] win=new int[128]; int left=0;int right=0; List<Integer> res=new ArrayList<>(); for(int i=0;i<p.length();i++){ need[p.charAt(i)]++;//将目标数组中各元素计数。 } while(right<s.length()){ win[s.charAt(right)]++;//窗口右移 while(right<s.length()&&win[s.charAt(right)]>need[s.charAt(right)]){//窗口停止右移条件 win[s.charAt(left)]--; left+;//窗口左移 } if(right-left+1==p.length()){ res.add(left); } right++; } return res; } }
标签:let input 嵌套循环 元素 ref nbsp string i++ 滑动
原文地址:https://www.cnblogs.com/NeverGiveUp0/p/12850775.html