Answer coming wrong for some test cases

user13066649 :

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.For test case below answer is coming wrong.

Input:
"aaaaaaabc"
"aaaaaaacb"
class Solution {
    public boolean buddyStrings(String A, String B)
    {
        int count=0,index=0;
        int a[] = new int[A.length()];
        if( A.length()!=B.length() )
            return false;
        if( A.equals(B) )
        {
            for(int i=0; i<A.length() ;i++)
            {
                if( A.charAt(0)==A.charAt(i) )
                    count++;
            }
            return( count==A.length() );
        }

        for(int i=0; i<A.length(); i++)
        {
            if(A.charAt(i) ! = B.charAt(i))
                a[index++] = i;
        }
         if( a.length==2 )
        {
            if(A.charAt(a[0])==B.charAt(a[1]) && A.charAt(a[1])==B.charAt(a[0]))
                return true;
            else
                return false;
        } 
        else
        return false;
    }
}
Shreya Malviya :

This part of your code is the problem.

if( A.equals(B) )
        {
            for(int i=0; i<A.length() ;i++)
            {
                if( A.charAt(0)==A.charAt(i) )
                    count++;
            }
            return( count==A.length() );
        }

Consider a case where A = B = "abcdefga".

According to your code, i takes up values from 0 to 7. The condition is only satisfied once, i.e. when i = 7, so count is equal to 1 when the loop is terminated. In your return statement, count == A.length() returns false because 1 =/= 7.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356015&siteId=1