C++ solution, easy to understand


  • 0
    M
    class Solution {
    public:
        bool isOneEditDistance(string s, string t) {
            if(s.length()==t.length()){
                int count = 0;
                for(int i=0;i<s.length();i++){
                    if(s[i]!=t[i])
                        count++;
                    if(count>1)
                        return false;
                }
                if(count == 1)
                return true;
                return false;
            }
            else if(abs(int(s.length()-t.length()))>1){
                return false;
            }
            else if(abs(int(s.length()-t.length())) == 1){
                int length = s.length();
                int count = 0;
                if(s.length()>t.length())
                    length = t.length();
                int j = 0;
                for(int i=0;i<length&&j<length+1;i++,j++){
                    if(length == s.length()){
                        if(s[i]!=t[j]){
                            count++;
                            i--;
                        }
                        if(count>1)
                            return false;
                    }
                    if(length == t.length()){
                        if(s[j]!=t[i]){
                            count++;
                            i--;
                        }
                        if(count>1)
                            return false;
                    }
                }
                if(count == 1 && j == length+1)
                return true;
                else if(count == 0)
                return true;
                else
                return false;
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.