Backspace String Compare - Leetcode

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.

Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac". 
 
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true 
 Explanation: Both S and T become "". 
 
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c". 
 
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b". 
 
Note:
  1. 1 <= S.length <= 200
  2. 1 <= T.length <= 200
  3. S and T only contain lowercase letters and '#' characters.
class Solution {
    public boolean backspaceCompare(String s, String t) {
       
        while(s.contains("#") || t.contains("#")){
            if(s.contains("#")){
                int i = s.indexOf("#");
                if(i==0)
                {
                    s = s.substring(1);
                }
                else{
                   s = s.substring(0,i-1)+s.substring(i+1);
                }
               
            }
           
            if(t.contains("#")){
                 int i = t.indexOf("#");
                if(i==0)
                {
                    t = t.substring(1);
                }
                else{
                   t = t.substring(0,i-1)+t.substring(i+1);
                }
            }
        }
        if(s.equals(t)){
            return true;
        }
        else{
            return false;
        }
       
    }
}


Here, we are doing same steps simultaneously for both the strings.
1)Check is string contains # using contains().
2) If it contains then find index position of # using indexOf().
3)Then using that index value backspace the nearby value using substring()[which has to be separated and merged without # character]. 

Try out this on Leetcode

Comments

Popular posts from this blog

First Unique Character in a String

Balanced Binary Tree

Majority Element

Sequential Digits