[Double pointer] 844. Compare strings with backspace

844. Compare Strings with Backspaces

problem solving ideas

insert image description here

Idea: The role of the function deLETE is to process strings with backspace symbols. It uses double pointer method to simulate string handling. Initially, both the slow pointer slow and the fast pointer fast point to the beginning of the string. Then, by traversing the string, if the current character is not a backspace sign (#), copy the character to the position where the slow pointer is, and the slow pointer slow moves backward one bit. If the current character is a backspace symbol, and the position of the slow pointer slow is greater than 0 (that is, it is not the beginning of the string), move the slow pointer forward by one bit, which is equivalent to deleting the previous character. Finally, return the processed string, and use the substr function to intercept the substring from the beginning to the slow pointer slow.

class Solution {
    
    
    public String delete(String s){
    
    
        // 使用快慢指针来删除元素 
        // 首先快慢指针同时指向字符串的末尾位置
        // 然后一起像前面移动  遇到非目标元素 都一起向前移动
        // 遇到目标元素之后 慢指针停下来 然后 快指针移动位置

        // 设置快慢指针 目标删除 # 元素还有前面一个元素
        int slow = 0;
        int fast = 0;
        char[] arr = s.toCharArray();// 转换为字符数组

        for(fast = 0; fast < s.length(); fast++){
    
    
            if(arr[fast] != '#'){
    
    
                // 快指针指向的元素 直接覆盖慢指针指向的元素 # 
                arr[slow] = arr[fast];
                // 然后slow ++
                slow++;
            }else if(slow > 0){
    
    
                slow--;// 这句话的目的在于   我们需要删除 # 前面一个字符
            }
        }

        return new String(arr,0,slow);// 返回新的字符串
    }
    public boolean backspaceCompare(String s, String t) {
    
    
        // 将两个字符串转换为 字符数组
        return delete(s).equals(delete(t));
    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/131627893