比较含退格的字符串-力扣

做这道题时出现了许多问题

  • 第一次做题思路是使用双指针去解决,快慢指针遇到字母则前进,遇到 # 则慢指针退1,最开始并未考虑到 slowindex < 0 ,从而导致越界。
  • 第二个问题在于,在最后判断两个字符串是否相同时,最初使用的判断方法是
if(s!=t){
    
    return false;}

但是由于并未重构两个字符串,两个字符串实际上可能并不相等,继而导致许多测试用例错误。
后选择逐个比较两个字符串 前慢指针个数 个元素的方法进行判断,具体代码如下:

class Solution {
    
    
public:
    bool backspaceCompare(string s, string t) {
    
    
        int slowindex = 0;
        int fastindex = 0;

        for(fastindex; fastindex < s.size(); fastindex++){
    
    
            if(s[fastindex] != '#'){
    
    
                s[slowindex++] = s[fastindex];
            }else {
    
    
                if(slowindex > 0){
    
    
                    slowindex--;
                }
            }
        }

        int slowindex2 = 0;
        int fastindex2 = 0;
        for(fastindex2; fastindex2 < t.size(); fastindex2++){
    
    
            if(t[fastindex2] != '#'){
    
    
                t[slowindex2++] = t[fastindex2];
            }else {
    
    
                if(slowindex2 > 0){
    
    
                    slowindex2--;
                }
            }
        }
        
        if(slowindex != slowindex2 ){
    
    
            return false;
        }
        for(int i=0; i < slowindex; i++)
            if(s[i]!=t[i]){
    
    
                return false;
            }
        return true;

        // if(s!=t){
    
    
            // return false;
        // }
        //return true;
    }
};

猜你喜欢

转载自blog.csdn.net/why_12134/article/details/139099708