当前位置:网站首页>Double pointer analog

Double pointer analog

2022-06-24 08:51:00 accumulate steadily ض

844. Compare strings with backspace

Use the double finger method to traverse the two strings respectively

  • Definition skip To record #, To offset
  • Define two pointers , Start traversing from back to front
  • There are three situations when two pointers are traversed        

          1. The first time I met #  ---> Record #

          2.skip The number of is not 0 --> Offset

          3. First encounter with non #--> Jump out of the loop and start comparing

  • Finally, compare the characters between the two strings
class Solution {
    public boolean backspaceCompare(String s, String t) {
         int skipS =0;// Record s In the string # No. quantity 
         int skipT =0;// Record t In the string # No. quantity 
         // Two pointers traverse the string from back to front 
         int i =s.length()-1;// Point to s--> Traversal string s
         int j =t.length()-1;// Point to t--> Traversal string t
         while(i>=0||j>=0){// Both strings are traversed before ending , Jump out of the loop to prove that the string is equal 
            // The string s To deal with 
            //1. The first time I met #  ---> Record #
            //2.skip The number of is not 0 --> Offset 
            //3. First encounter with non #--> Jump out of the loop and start comparing 
            while(i>=0){
                if(s.charAt(i)=='#') {
                    skipS++;
                    i--;
                }else if(skipS>0) {
                    skipS--;
                    i--;
                }else {
                    break;
                }
            }
            // Same for j Do the same thing 
            while(j>=0){
                if(t.charAt(j)=='#'){
                    skipT++;
                    j--;
                }else if(skipT>0){
                    skipT--;
                    j--;
                }else {
                    break;
                }
            }
            // At this point, the strings are processed accordingly, and then the two strings are compared 
            if(i>=0&&j>=0){
                if(s.charAt(i)!=t.charAt(j)){
                    // Two characters are not equal 
                    return false;
                }
            }else {
                if((i>=0&&j<0)||(j>=0&&i<0)){
                    // Prove that a string has exceeded the limit 
                    return false;
                }
            }
            // Continue traversing the string 
            i--;
            j--;
         }
         return true;
    }
}

原网站

版权声明
本文为[accumulate steadily ض]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240637108591.html