去除有序数组中的重复元素,快慢指针
int removeDuplicates(int[] nums){
int n = nums.length;
if(n == 0) return 0;
int slow = 0;
int fast = 1;
while(fast < n){
if(nums[fast]==nums[slow]]{
slow++;
nums[slow] = num[fast];
}
}
return slow + 1;
}
最长回文串,左右指针中心扩展
String longestStr(String s){
char[] chars = new char[s.length()];
String str = null;
for(int i=0;i<s.length(),i++){
chars[i] = s.charAt[i];
}
for(int i = 1;i<chars.length;i++){
str1=pilidrome(s,i,i);
str2=pilidrome(s,i,i+!);
str = str.length()>str1.length()?str:str1;
str = str.length()>str2.length()?str:str2;
}
retrun str;
}
String palindrome(String s, int l ,int r){
while(l>0 && r< s.length() && s[l] == s[r]){
l--;r++;
}
return s.substr(l+1,r-l-r);
}
判断是否为回文字符串
boolean isPalidrome(String s){
int left = 0; right =s.length()-1;
while(left<right){
if(s[left] != s[right]){
return false;
}
left++;right--;
}
return ture;
}
通过双指针可以找链表或者数组的中点,或者环
ListNode slow, fast;
slow = fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
boolean hasCycle(ListNode head) {
ListNode fast, slow;
fast = slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) return true;
}
return false;
}
返回环的起点
ListNode detectCycle(ListNode head) {
ListNode fast, slow;
fast = slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) break;
}
// 上面的代码类似 hasCycle 函数
slow = head;
while (slow != fast) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
滑动窗口
最小覆盖子串
string minWindow(string s, string t) {
// 记录最短子串的开始位置和长度
int start = 0, minLen = INT_MAX;
int left = 0, right = 0;
unordered_map<char, int> window;
unordered_map<char, int> needs;
for (char c : t) needs[c]++;
int match = 0;
while (right < s.size()) {
char c1 = s[right];
if (needs.count(c1)) {
window[c1]++;
if (window[c1] == needs[c1])
match++;
}
right++;
while (match == needs.size()) {
if (right - left < minLen) {
// 更新最小子串的位置和长度
start = left;
minLen = right - left;
}
char c2 = s[left];
if (needs.count(c2)) {
window[c2]--;
if (window[c2] < needs[c2])
match--;
}
left++;
}
}
return minLen == INT_MAX ?
"" : s.substr(start, minLen);
}
无重复最长子串
int lengthOfLongestSubstring(string s) {
int left = 0, right = 0;
unordered_map<char, int> window;
int res = 0; // 记录最长长度
while (right < s.size()) {
char c1 = s[right];
window[c1]++;
right++;
// 如果 window 中出现重复字符
// 开始移动 left 缩小窗口
while (window[c1] > 1) {
char c2 = s[left];
window[c2]--;
left++;
}
res = max(res, right - left);
}
return res;
}