Detailed Explanation of the Ruler Method in Programming Contest

Table of contents

1. What is the ruler method

2. How to use the ruler method

3. Advantages and application scenarios of the ruler method


 

1. What is the ruler method

Two Pointers Technique is a common algorithmic technique used to solve some array or string related problems . This method solves the problem by using two pointers (rulers) to point to different positions of the array or string, and adjusting the positions of the two pointers.

The basic idea of ​​the ruler method is to transform the problem into a certain relationship between two pointers by traversing the array or string. By moving the positions of the pointers, the distance between the two pointers is constantly adjusted to meet the requirements of the problem.

Common application scenarios of the ruler method include the following:

  1. Sliding window problem: Define a window by maintaining two pointers, and solve related problems by continuously adjusting the position and size of the window. For example, problems such as the smallest covering substring, the longest non-repeating character substring, etc.
  2. Fast and slow pointer problem: Solve related problems by maintaining two pointers, one fast pointer and one slow pointer, and through different moving strategies. For example, judging whether the linked list has a ring, finding the intermediate node of the linked list, etc.
  3. The problem of merging two ordered arrays: by maintaining two pointers, pointing to the end of the two ordered arrays respectively, by comparing the sizes and putting the larger elements into the merged array in turn, the merge problem is solved.

The advantage of the ruler method lies in its simple and efficient algorithm idea, which is suitable for solving many problems. By reasonably setting the starting positions of the two pointers and adjusting the pointer movement strategy according to the requirements of the problem, some complex array or string-related problems can be quickly solved.

 

2. How to use the ruler method

The following is an example of Java sample code using the ruler method to solve the sliding window problem (find the minimum covering substring):

import java.util.HashMap;
import java.util.Map;

public class TwoPointersExample {
    public static String minWindow(String s, String t) {
        // 使用HashMap存储目标字符串中每个字符的出现次数
        Map<Character, Integer> target = new HashMap<>();
        for (char c : t.toCharArray()) {
            target.put(c, target.getOrDefault(c, 0) + 1);
        }
        
        int left = 0;   // 左指针
        int right = 0;  // 右指针
        int count = 0;  // 计数器,用于记录满足条件的字符个数
        int minLen = Integer.MAX_VALUE;  // 最小覆盖子串的长度
        int minStart = 0;  // 最小覆盖子串的起始位置
        Map<Character, Integer> window = new HashMap<>();  // 存储当前窗口内的字符及其出现次数
        
        while (right < s.length()) {
            char c = s.charAt(right);  // 移动右指针,扩展窗口
            window.put(c, window.getOrDefault(c, 0) + 1);
            if (target.containsKey(c) && window.get(c).intValue() == target.get(c).intValue()) {
                // 当窗口内某个字符数量满足要求时,更新计数器
                count++;
            }
            
            while (count == target.size()) {
                // 当窗口内的字符满足要求时,移动左指针,缩小窗口
                if (right - left + 1 < minLen) {
                    minLen = right - left + 1;
                    minStart = left;
                }
                char leftChar = s.charAt(left);
                window.put(leftChar, window.get(leftChar) - 1);
                if (target.containsKey(leftChar) && window.get(leftChar).intValue() < target.get(leftChar).intValue()) {
                    // 当窗口内某个字符数量不满足要求时,更新计数器
                    count--;
                }
                left++;
            }
            
            right++;
        }
        
        return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen);
    }

    public static void main(String[] args) {
        String s = "ADOBECODEBANC";
        String t = "ABC";
        String result = minWindow(s, t);
        System.out.println("最小覆盖子串为: " + result);
    }
}

The above code maintains a sliding window (left pointer and right pointer), and uses HashMap to count the number of occurrences of characters in the window. When the characters in the window meet the conditions, move the left pointer to shrink the window, and record the starting position and length of the minimum covered substring. Finally returns the smallest covering substring. This is a typical application example of the ruler method.

 

3. Advantages and application scenarios of the ruler method

The advantages of the ruler method include the following:

  1. Low time complexity: The ruler method usually traverses the array or string by maintaining two pointers, and each element is processed at most once, so the time complexity is usually O(N), where N is the number of elements.

  2. Low space complexity: The ruler method usually only needs to use a constant level of extra space (such as two pointers), and does not require additional arrays or data structures.

  3. The idea of ​​the algorithm is simple: the idea of ​​the ruler method is relatively intuitive, easy to understand and implement.

The ruler method is applicable to the following scenarios:

  1. Sliding window problem: The ruler method is often used to solve the sliding window problem, that is, sliding in a fixed-size window, and solving the problem by adjusting the position and size of the window. For example, problems such as finding the smallest covering substring, longest contiguous subarray, etc.

  2. Fast and slow pointer problem: The ruler method is also commonly used to solve the fast and slow pointer problem. By maintaining two pointers, one fast pointer and one slow pointer, related problems are solved through different moving strategies. For example, judging whether the linked list has a ring, finding the intermediate node of the linked list, etc.

  3. Ordered array merging problem: The ruler method can be used to merge two ordered arrays, by maintaining two pointers, pointing to the end of the two ordered arrays, by comparing the size and putting the larger elements into the merged one by one In the array, solve the merge problem.

In general, the ruler method is suitable for scenarios that need to traverse arrays or strings and solve problems by maintaining the positions of two pointers . Its advantage lies in its simplicity, high efficiency, and it is suitable for solving various practical problems.

Guess you like

Origin blog.csdn.net/2301_77899321/article/details/131600037