代码随想录学习记录


一、数组

1. 704-二分查找

二分查找

class Solution {
    public int search(int[] nums, int target) {
        // 边界判断
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        // 不存在的情况
        return -1;
    }
}

2. 35-搜索插入位置

搜索插入位置

class Solution {
    public int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int left = 0, right = nums.length - 1;
        int mid = 0;
        while (left <= right) {
            mid = left + ((right - left) >> 1);
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return nums[mid] > target ? mid : mid + 1;
    }
}

3. 34-在排序数组中查找元素的第一个和最后一个位置

在排序数组中查找元素的第一个和最后一个位置

class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[] { -1, -1 };
        }
        // 判断目标是否在数组中
        int res = binarySearch(nums, target);
        if (res == -1) {
            return new int[] { -1, -1 };
        }

        int left = res;
        int right = res;
        // 注意边界控制
        while (left > 0 && nums[left - 1] == target) {
            --left;
        }
        while (right < nums.length - 1 && nums[right + 1] == target) {
            ++right;
        }
        return new int[] {left, right};
    }

    public static int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        // 不存在的情况
        return -1;
    }
}

4. 69-X 的平方根

X 的平方根

class Solution {
    public int mySqrt(int x) {
        int left = 0, right = x;
        int mid = 0;
        while (left <= right) {
            mid = left + ((right - left) >> 1);
            if ((long) mid * mid > x) {
                right = mid - 1;
            } else if ((long) mid * mid < x) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return right;
    }
}

5. 367-有效的完全平方数

有效的完全平方数

class Solution {
    public boolean isPerfectSquare(int num) {
        int left = 0, right = num;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if ((long) mid * mid > num) {
                right = mid - 1;
            } else if ((long) mid * mid < num) {
                left = mid + 1;
            } else {
                return true;
            }
        }
        return false;
    }
}

6. 27-移除元素

移除元素

class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int start = 0;
        for (int cur = start; cur < nums.length; ++cur) {
            if (nums[cur] == val) {
                continue;
            }
           
            nums[start] = nums[cur];
            ++start;

        }
        return start; // 返回的是长度,start 是下标
    }
}

7. 26-删除有序数组中的重复项

移除元素

class Solution {
    public int removeDuplicates(int[] nums) {
        int start = 0;
        for (int cur = start + 1; cur < nums.length; ++cur) {
            if (nums[cur] == nums[start]) {
                continue;
            }
            nums[++start] = nums[cur];
        }
        return start + 1;
    }
}

8. 283-移动零

移动零

class Solution {
    public void moveZeroes(int[] nums) {
        int start = 0;
        for (int cur = start; cur < nums.length; ++cur) {
            if (nums[cur] == 0) {
                continue;
            }
            int tmp = nums[start];
            nums[start++] = nums[cur];
            nums[cur] = tmp;
        
        }

    }
}

9. 844-比较含退格的字符串

比较含退格的字符串

class Solution {
    public boolean backspaceCompare(String s, String t) {
        return getString(s).equals(getString(t));
    }

    public static String getString(String str) {
        char[] arr = str.toCharArray();
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < arr.length; ++i) {
            char ch = arr[i];
            if (ch != '#') {
                buf.append(ch);
            } else {
                if (buf.length() > 0) {
                    buf.deleteCharAt(buf.length() - 1);
                }
            }
        }
        return buf.toString();
    }
}

10. 977-有序数组的平方

有序数组的平方

class Solution {
    public int[] sortedSquares(int[] nums) {
        int n = nums.length;
        int[] ans = new int[n];
        int pos = n - 1;
        int left = 0, right = n - 1;
        while (left <= right) {
            if (nums[left] * nums[left] >= nums[right] * nums[right]) {
                ans[pos--] = nums[left] * nums[left];
                ++left;
            } else {
                ans[pos--] = nums[right] * nums[right];
                --right;
            }
        }
        return ans; 
    }
}

11. 209-长度最小的子数组

长度最小的子数组

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0;
        int sum = 0;
        int ans = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; ++right) {
            sum += nums[right];
            while (sum >= target) {
                ans = Math.min(ans, right - left + 1);
                sum -= nums[left++];
            }
        }

        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}

12. 904-水果成篮

水果成篮

class Solution {
    public int totalFruit(int[] fruits) {
        Map<Integer, Integer> fruitMap = new HashMap<>();
        int left = 0;
        int ans = 0;
        for (int right = 0; right < fruits.length; ++right) {
            fruitMap.put(fruits[right], fruitMap.getOrDefault(fruits[right], 0) + 1);
            while (fruitMap.size() > 2) {
                fruitMap.put(fruits[left], fruitMap.get(fruits[left]) - 1);
                // 若该种类数量为0, 则去除该种类
                if (fruitMap.get(fruits[left]) == 0) {
                    fruitMap.remove(fruits[left]);
                }
                ++left;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }
}

13. 76-最小覆盖字串

最小覆盖字串

class Solution {
    public String minWindow(String s, String t) {
        Map<Character, Integer> window = new HashMap<>();
        Map<Character, Integer> need = new HashMap<>();
        for (int i = 0; i < t.length(); ++i) {
            char ch = t.charAt(i);
            need.put(ch, need.getOrDefault(ch, 0) + 1);
        }
        int left = 0;
        int valid = 0;
        int start = 0; // 记录起点
        int ans = Integer.MAX_VALUE;
        for (int right = 0; right < s.length(); ++right) {
            char ch = s.charAt(right);
            // 判断该字符是否在 need 中
            if (need.containsKey(ch)) {
                window.put(ch, window.getOrDefault(ch, 0) + 1);
                if (window.get(ch) == need.get(ch)) {
                    ++valid;
                }
            }

            while (valid == need.size()) {
                char c = s.charAt(left);
                // 更新字串长度
                if (right - left < ans) {
                    ans = right - left;
                    start = left;
                }
                if (need.containsKey(c)) {
                    window.put(c, window.get(c) - 1);
                    if (window.get(c) < need.get(c)) {
                        --valid;
                    }
                }
                ++left;
            }
        }

        return ans == Integer.MAX_VALUE ? "" : s.substring(start, start + ans + 1);
    }
}

14. 59-螺旋矩阵II

螺旋矩阵II

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int top = 0, bottom = n - 1;
        int left = 0, right = n - 1;
        int count = 1;
        while (top <= bottom && left <= right) {
            for (int j = left; j <= right; ++j) {
                matrix[top][j] = count++;
            }

            for (int i = top + 1; i <= bottom; ++i) {
                matrix[i][right] = count++;
            }

            if (top < bottom && left < right) {
                for (int j = right - 1; j >= left; --j) {
                    matrix[bottom][j] = count++;
                }

                for (int i = bottom - 1; i >= top + 1; --i) {
                    matrix[i][left] = count++;
                }
            }

            ++top;
            --right;
            ++left;
            --bottom;
        }
        return matrix;
    }
}

15. 54-螺旋矩阵

螺旋矩阵

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        List<Integer> nums = new ArrayList<>();
        int top = 0, right = n - 1;
        int left = 0, bottom = m - 1;
        while (top <= bottom && left <= right) {
            for (int j = left; j <= right; ++j) {
                nums.add(matrix[top][j]);
            }

            for (int i = top + 1; i <= bottom; ++i) {
                nums.add(matrix[i][right]);
            }

            if (top < bottom && left < right) {
                for (int j = right - 1; j >= left; --j) {
                    nums.add(matrix[bottom][j]);
                }

                for (int i = bottom - 1; i >= top + 1; --i) {
                    nums.add(matrix[i][left]);
                }
            }

            ++top;
            --right;
            ++left;
            --bottom;
        }
        return nums;
    }
}

16. LCR-146-螺旋遍历二维数组

螺旋矩阵

class Solution {
    public int[] spiralArray(int[][] array) {
        if (array == null || array.length == 0 || array[0].length == 0) {
            return new int[0];
        }
        int m = array.length;
        int n = array[0].length;
        int[] nums = new int[m * n];
        int top = 0, right = n - 1;
        int left = 0, bottom = m - 1;
        int index = 0;
        while (top <= bottom && left <= right) {
            for (int j = left; j <= right; ++j) {
                nums[index++] = array[top][j];
            }

            for (int i = top + 1; i <= bottom; ++i) {
                nums[index++] = array[i][right];
            }

            if (top < bottom && left < right) {
                for (int j = right - 1; j >= left; --j) {
                    nums[index++] = array[bottom][j];
                }

                for (int i = bottom - 1; i >= top + 1; --i) {
                    nums[index++] = array[i][left];
                }
            }

            ++top;
            --right;
            ++left;
            --bottom;
        }
        return nums;
    }
}

二. 链表

1. 203-移除链表元素

移除链表元素

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummyHead = new ListNode();
        dummyHead.next = head;
        ListNode cur = dummyHead;
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return dummyHead.next;
    }
}

2. 707-设计链表

设计链表

public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class MyLinkedList {

    private int size;
    private ListNode head = new ListNode();

    public MyLinkedList() {

    }

    public int get(int index) {
        // 边界判断
        if (index < 0 || index >= size) {
            return -1;
        }

        ListNode cur = head;
        for (int i = 0; i < index + 1; ++i) {
            cur = cur.next;
        }

        return cur.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    public void addAtTail(int val) {
        addAtIndex(size, val);
    }

    public void addAtIndex(int index, int val) {
        if (index > size) {
            return;
        }
        index = Math.max(index, 0);
        ++size;
        ListNode prev = head;
        for (int i = 0; i < index; ++i) {
            prev = prev.next;
        }
        ListNode node = new ListNode(val);
        node.next = prev.next;
        prev.next = node;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        --size;
        ListNode prev = head;
        for (int i = 0; i < index; ++i) {
            prev = prev.next;
        }
        prev.next = prev.next.next;
    }
}

3. 206-反转链表

反转链表

class Solution {
    public ListNode reverseList(ListNode head) {
    	 ListNode prev = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }

        return prev;
    }
}

4. 24-两两交换链表中的节点

两两交换链表中的节点

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            int tmp = cur.val;
            cur.val = cur.next.val;
            cur.next.val = tmp;
            cur = cur.next.next;
        }
        return head;
    }
}

5. 19-删除链表的倒数第N个节点

删除链表的倒数第N个节点

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode();
        dummyHead.next = head;
        ListNode fast = head;
        ListNode slow = dummyHead;
        // n 大于 链表长度
        for (int i = 0; i < n; ++i) {
            fast = fast.next;
        }

        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }

        slow.next = slow.next.next;

        return dummyHead.next;
    }
}

6. 面试题 02.07. 链表相交

面试题 02.07. 链表相交

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }

        int lenA = getListLen(headA);
        int lenB = getListLen(headB);

        ListNode slow = (lenA <= lenB) ? headA : headB;
        ListNode fast = (slow == headA) ? headB : headA;

        for (int i = 0; i < Math.abs(lenA - lenB); ++i) {
            fast = fast.next;
        }

        while (slow != null && fast != null) {
            if (slow == fast) {
                return fast;
            }
            slow = slow.next;
            fast = fast.next;
        }
        return null;

    }

    public int getListLen(ListNode head) {
        int len = 0;
        while (head != null) {
            ++len;
            head = head.next;
        }
        return len;
    }
}

7. 142-环形链表II

环形链表II

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            // 有环
            if (slow == fast) {
                ListNode p = head;
                ListNode q = fast;
                while (p != q) {
                    p = p.next;
                    q = q.next;
                }
                return p;
            }

        }

        return null;
    }
}

三. 哈希表

1. 242-有效的字母异位词

有效的字母异位词

class Solution {
    public boolean isAnagram(String s, String t) {
        // 排序
        if (s.length() != t.length()) {
            return false;
        }

        char[] s1 = s.toCharArray();
        char[] t1 = t.toCharArray();
        Arrays.sort(s1);
        Arrays.sort(t1);
        return Arrays.equals(s1, t1);
    }
}
class Solution {
    public boolean isAnagram(String s, String t) {
        int[] nums = new int[26];

        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            nums[ch - 'a']++;
        }

        for (int i = 0; i < t.length(); ++i) {
            char ch = t.charAt(i);
            nums[ch - 'a']--;
            if (nums[ch - 'a'] < 0) {
                return false;
            }
        }

        return true;
    }
}

2. 383-赎金信

赎金信

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] nums = new int[26];

        for (int i = 0; i < magazine.length(); ++i) {
            char ch = magazine.charAt(i);
            nums[ch - 'a']++;
        }

        for (int i = 0; i < ransomNote.length(); ++i) {
            char ch = ransomNote.charAt(i);
            nums[ch - 'a']--;
            if (nums[ch - 'a'] < 0) {
                return false;
            }
        }
        return true;
    }
}

3. 49-字母异位词分组

字母异位词分组

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        // 遍历字符串,将排序后的字符串作为 key
        for (String str: strs) {
            char[] strArray = str.toCharArray();
            Arrays.sort(strArray);
            String key = new String(strArray);
            List<String> list = map.getOrDefault(key, new ArrayList<>());
            list.add(str);
            map.put(key, list);
        }

        return new ArrayList<>(map.values());
    }
}

4. 438-找到字符串中所有字母异位词

找到字符串中所有字母异位词

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        // 记录 p 中的 字母以及出现的次数
        int[] cnt = new int[26];

        for (char c : p.toCharArray()) {
            cnt[c - 'a']++;
        }

        // 使用滑窗思想来遍历 s 字符串
        int left = 0;
        int right = 0;
        List<Integer> res = new ArrayList<>();
        while (right < s.length()) {
            if (cnt[s.charAt(right) - 'a'] > 0) {
                cnt[s.charAt(right) - 'a']--;
                ++right;
                if (right - left == p.length()) {
                    res.add(left);
                }
            } else {
                cnt[s.charAt(left) - 'a']++;
                ++left;
            }
        }

        return res;
    }
}

5. 349-两个数组的交集

两个数组的交集

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            intersection(nums2, nums1);
        }

        Set<Integer> set = new HashSet<>();
        for (int num : nums1) {
            set.add(num);
        }

        Set<Integer> ans = new HashSet<>();

        for (int num : nums2) {
            if (set.contains(num)) {
                ans.add(num);
            }
        }

        int index = 0;
        int[] res = new int[ans.size()];

        for (int num: ans) {
            res[index++] = num;
        }

        return res;
    }
}

6. 202-快乐数

快乐数

class Solution {
    public boolean isHappy(int n) {
        int slow = n;
        int fast = getNext(n);

        while (fast != 1 && slow != fast) {
            slow = getNext(slow);
            fast = getNext(getNext(fast));
        }

        return fast == 1;
    }

    public int getNext(int n) {
        int sum = 0;
        while (n > 0) {
            int tmp = n % 10;
            sum += tmp * tmp;
            n /= 10;
        }

        return sum;
    }
}

7. 1-两数之和

两数之和

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map <Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; ++i) {
            if (map.containsKey(target - nums[i])) {
                return new int[] {map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }

        return new int[0];
    }
}

8. 454-四数相加II

四数相加II

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int n = nums1.length;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                map.put(nums1[i] + nums2[j], 
                map.getOrDefault(nums1[i] + nums2[j], 0) + 1);
            }
        }

        int res = 0;
        for (int k = 0; k < n; ++k) {
            for (int l = 0; l < n; ++l) {
                if (map.containsKey(-(nums3[k] + nums4[l]))) {
                    res += map.get(-(nums3[k] + nums4[l]));
                }
            }
        }

        return res;
    }
}

9. 15-三数之和

三数之和

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        // 边界判断
        if (nums.length < 3 || nums == null) {
            return res;
        }

        int n = nums.length;

        // 将数组进行排序
        Arrays.sort(nums);
        for (int i = 0; i < n; ++i) {
            // 如果起始元素大于 0, 则三数之和一定大于 0 (有序)
            if (nums[i] > 0) {
                break;
            }

            // 判断是否与前一个元素相同,避免重复
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int left = i + 1;
            int right = n - 1;

            while (left < right) {
                // 将三数相加
                int sum = nums[i] + nums[left] + nums[right];

                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    // 移动 left 与 right,移动前同样进行去重判断
                    while (left < right && nums[left] == nums[left + 1]) {
                        ++left;
                    }

                    while (left < right && nums[right] == nums[right - 1]) {
                        --right;
                    }

                    ++left;
                    --right;
                } else if (sum < 0) {
                    ++left;
                } else if (sum > 0) {
                    --right;
                }
            }
        }

        return res;
    }
}

10. 18-四数之和

四数之和

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();

        if (nums == null || nums.length < 4) {
            return res;
        }

        Arrays.sort(nums);
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] > 0 && nums[i] > target) {
                break;
            }

            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            for (int j = i + 1; j < nums.length; ++j) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }

                int l = j + 1;
                int r = nums.length - 1;

                while (l < r) {
                    long sum = (long) nums[i] + nums[j] + nums[l] + nums[r];

                    if (sum == target) {
                        res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
                        while (l < r && nums[l] == nums[l + 1]) {
                            ++l;
                        }

                        while (l < r && nums[r] == nums[r - 1]) {
                            --r;
                        }

                        ++l;
                        --r;
                    } else if (sum < target) {
                        ++l;
                    } else if (sum > target) {
                        --r;
                    }
                }
            }
        }

        return res;
    }
}

四. 字符串

1. 344-反转字符串

反转字符串

class Solution {
    public void reverseString(char[] s) {
        int l = 0;
        int r = s.length - 1;

        while (l < r) {
            char tmp = s[l];
            s[l++] = s[r];
            s[r--] = tmp;
        }
    }
}

2. 541-反转字符串II

反转字符串II

class Solution {
    public String reverseStr(String s, int k) {
        int n = s.length();
        char[] arr = s.toCharArray();
        for (int i = 0; i <= n; i += 2 * k) {
            reverse(arr, i, Math.min(i + k, n) - 1);
        }

        return new String(arr);
    }

    public void reverse(char[] arr, int l, int r) {
        while (l < r) {
            char tmp = arr[l];
            arr[l++] = arr[r];
            arr[r--] = tmp;
        }
    }

}

3. KamaCoder54-替换数字

替换数字

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        StringBuilder sb = getStringBuilder(s);
        System.out.println(sb);
    }
    
    public static StringBuilder getStringBuilder(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') {
                sb.append(s.charAt(i));
            } else {
                sb.append("number");
            }
        }
        
        return sb;
    }
}

4.151-反转在字符串中的单词

反转在字符串中的单词

class Solution {
    public String reverseWords(String s) {
        // 1. 得到去除多余空格的字符串
        StringBuilder sb = removeSpace(s);

        // 2. 反转整个字符串
        int l = 0;
        int r = sb.length() - 1;
        reverse(sb, l, r);

        // 3. 反转每个单词
        reverseWord(sb);

        return sb.toString();
    }

    public StringBuilder removeSpace(String s) {
        StringBuilder sb = new StringBuilder();
        int l = 0;
        int r = s.length() - 1;
    
        while (l <= r && s.charAt(l) == ' ') {
            ++l;
        }

        while (l <= r && s.charAt(r) == ' ') {
            --r;
        }

        while (l <= r) {
            char c = s.charAt(l);

            if (c != ' ') {
                sb.append(c);
            } else if (sb.charAt(sb.length() - 1) != ' ') {
                sb.append(c);
            }

            ++l;
        }

        return sb;
    }

    public void reverse(StringBuilder sb, int l, int r) {
        while (l < r) {
            char tmp = sb.charAt(l);
            sb.setCharAt(l, sb.charAt(r));
            sb.setCharAt(r, tmp);
            ++l;
            --r;
        }
    }

    public void reverseWord(StringBuilder sb) {
        int l = 0;
        int r = sb.length();
        int cur = 0;
        while (l < r) {
            while (cur < r && sb.charAt(cur) != ' ') {
                ++cur;
            }

            reverse(sb, l, cur - 1);

            l = cur + 1;

            // 此时 cur 位于空格,因此需要 ++
            ++cur;
        }
    }
}

5. 55-右旋字符串

右旋字符串

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int k = sc.nextInt();
        String s = sc.next();
        char[] arr = s.toCharArray();
        int n = s.length();
        // 旋转前面
        revrese(arr, 0, n - k - 1);
        
        // 旋转后面
        revrese(arr, n - k, n - 1);
        
        // 旋转整体
        revrese(arr, 0, n - 1);
        
        System.out.println(new String(arr));
    }
    
    public static void revrese(char[] arr, int start, int end) {
        while (start <= end) {
            char tmp = arr[start];
            arr[start++] = arr[end];
            arr[end--] = tmp;
        }
    }
}

6. 28-找出字符串中第一个匹配的下标

找出字符串中第一个匹配的下标

class Solution {
    public int strStr(String haystack, String needle) {
        // 暴力求解
        int n = haystack.length();
        int m = needle.length();
        for (int i = 0; i + m <= n; ++i) {
            boolean flag = true;
            for (int j = 0; j < m; ++j) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    flag = false;
                    break;
                }
            }

            if (flag) {
                return i;
            }
        }

        return -1;
    }
}
class Solution {
    public int strStr(String haystack, String needle) {
        // KMP 算法

        // 获得 next 数组
        int[] next = getKMPNext(needle);

        for (int i = 0, j = 0; i < haystack.length(); ++i) {

            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }

            if (haystack.charAt(i) == needle.charAt(j)) {
                ++j;
            }

            if (j == needle.length()) {
                return i - j + 1;
            }

        }

        return -1;
    }

    public int[] getKMPNext(String s) {
        int[] next = new int[s.length()];
        next[0] = 0;

        for (int i = 1, j = 0; i < s.length(); ++i) {
            while (j > 0 && s.charAt(i) != s.charAt(j)) {
                j = next[j - 1];
            }

            if (s.charAt(i) == s.charAt(j)) {
                ++j;
            }

            next[i] = j;
        }
        return next;
    }
}

7. 459-重复的子字符串

重复的子字符串

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        // 暴力求解
        int n = s.length();
        for (int i = 1; 2 * i <= n; ++i) {
            if (n % i == 0) {
                boolean flag = true;
                for (int j = i; j < n; ++j) {
                    if (s.charAt(j) != s.charAt(j - i)) {
                        flag = false;
                        break;
                    }
                }

                if (flag) {
                    return true;
                }
            }
        }

        return false;
    }
}
class Solution {
    public boolean repeatedSubstringPattern(String s) {
        // 移动匹配
        return (s + s).indexOf(s, 1) != s.length();
    }
}
class Solution {
    public boolean repeatedSubstringPattern(String s) {
        // KMP
        int[] next = getNext(s);

        int n = s.length();
        if (next[n - 1] != 0 && (n % (n - next[n - 1]) == 0)) {
            return true;
        }

        return false;
    }

    public int[] getNext(String s) {
        int n = s.length();
        int[] next = new int[s.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < n; ++i) {
            while (j > 0 && s.charAt(i) != s.charAt(j)) {
                j = next[j - 1];
            }

            if (s.charAt(i) == s.charAt(j)) {
                ++j;
            }

            next[i] = j;
        }

        return next;
    }
}
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值