双指针技巧数组题目

题目 难度 要点
删除有序数组中的重复项 快指针与慢指针值不同,那么应该将值放在慢指针下一位
移除元素 快指针对应值若不需移除,那么应该将值放在当前慢指针
最长回文子串 以当前位置或者当前位置及相邻位置扩散寻找回文子串

删除有序数组中的重复项

class Solution {
    public int removeDuplicates(int[] nums) {
        int slow = 0;
        int fast = 0;
        while (fast < nums.length) {
            if (nums[slow] != nums[fast]) {
                slow++;
                nums[slow] = nums[fast];
            }
            fast++;
        }
        return slow + 1;
    }
}

移除元素

class Solution {
    public int removeElement(int[] nums, int val) {
        int left = 0, right = 0;
        while (right < nums.length) {
            if (nums[right] != val) {
                nums[left] = nums[right];
                left++;
            }
            right++;
        }
        return left;
    }
}

最长回文子串

class Solution {
    public String longestPalindrome(String s) {
        String res = "";
        for (int i = 0; i < s.length(); i++) {
            String s1 = getPalindrome(s, i, i);
            String s2 = getPalindrome(s, i, i + 1);
            res = res.length() < s1.length()? s1: res;
            res = res.length() < s2.length()? s2: res;
        }
        return res;
    }

    private String getPalindrome(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return s.substring(left + 1, right);
    }
}
posted @ 2023-03-11 20:26  kiper  阅读(12)  评论(0编辑  收藏  举报