Search code examples
javalogic

Counting equal elements characters in java


I'm doing some exercises on codeforces and learning java. And i came across this deviation in solution results. When i test them in my console they work as intended but only one works on codeforces judge. There's this code(that can pass the tests, in java): https://codeforces.com/contest/1005/submission/208626855

And this one, that can't pass test 6 and probably many others: https://codeforces.com/contest/1005/submission/208624411

Test 6 is something like, input:

-string a:"aaaaaaaaaaaaa"... 399991 times

-string b:""

Output: mine(in codeforces is 5) and real one is 399991.

I don't know what differences are happening and don't know where can I ask this besides here, thank you for the help.


Solution

  • The task is basically to find the common tail of two strings and print the number of characters of both strings that are not part of the common tail. This is the code we are talking about.

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String a=br.readLine();
            String b=br.readLine();
            char [] arrA = a.toCharArray();
            char [] arrB = b.toCharArray();
            long count =0;
            if(arrA.length>arrB.length) count = arrA.length-arrB.length;
            else count = arrB.length-arrA.length;
    

    count is the difference in length of both strings. The beginning of the longer string cannot be part of the common tail. But this for loop is wrong:

            for(int i=0;i<Math.min(arrA.length,arrB.length);i++) {
                if(arrA[arrA.length-1-i]!=arrB[arrB.length-1-i]) count=count+2;
            }
            
            System.out.println(count);
    

    You iterate backwards and idle as long as the characters of both strings match. However, once they differ, you must add them, regardless of whether they match again or not. Consider

    ABA
    ACA
    

    This version will print 2 instead of the correct 4, because it counts B and C, but not the first two A. You could fix it like this

            boolean commonTail = true;
            for(int i=0;i<Math.min(arrA.length,arrB.length);i++) {
                if(arrA[arrA.length-1-i]!=arrB[arrB.length-1-i])
                    commonTail = false;
                if(!commonTail)
                    count=count+2;
            }
            System.out.println(count);