Vince
Vince

Reputation: 43

How to make this code become more effcient?

So I have been doing competitive programming using java, my code is ACCEPTED in codeforces. But I still think this code doesn't look so good, cause it needs 2 "for loops" to identify the duplication. if it is only one "for loops", it still has duplication in the strings.

This is the problem: https://codeforces.com/problemset/problem/236/A.

So basically, the code will try to find the distinct characters in the strings, then if the length of the string is odd, it will print "IGNORE HIM", else "CHAT WITH HER!".

import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
        String a;
    
        int counter=0;
        Scanner sc= new Scanner(System.in);
        a=sc.next();
        StringBuilder b= new StringBuilder(a);
        int count = 0;
    
        for(int i=0;i<b.length();i++)
        {
            for(int j=i+1;j<b.length();j++) {
                if(b.charAt(i)==b.charAt(j)) {
                    b=b.deleteCharAt(j);
                }
    
            }
        }
            for(int i=0;i<b.length();i++)
            {
                for(int j=i+1;j<b.length();j++) {
                    if(b.charAt(i)==b.charAt(j)) {
                        b=b.deleteCharAt(j);
                    }
    
                }
            }
    
        counter=b.length();
        if(counter%2==0)
        {
            System.out.println("CHAT WITH HER!");
    
        }
        else
        {
            System.out.println("IGNORE HIM!");
        }
        }
    }

Upvotes: 0

Views: 97

Answers (4)

tune5ths
tune5ths

Reputation: 723

I would use a Hashset because it will contain a distinct set of all characters you add. You can just go through the list once and use size() to get the unique character count.

...
Set<Character> characters = new HashSet<>()
for(int i=0;i<b.length();i++)
{
     characters.add(b.charAt(i));
}
if(characters.size()%2==0) {
...

Upvotes: 1

Abra
Abra

Reputation: 20914

Building upon and completing @Guillaume's answer

String a = "xiaodao";
String out = a.chars().distinct().count() % 2 == 0 ? "CHAT WITH HER!" : "IGNORE HIM!";
System.out.println(out);

Upvotes: 1

behold
behold

Reputation: 556

Using streams is a good option. If you want to go plain old route, then you can use a hashset. Basically if character is in hashset, then move to next char, else add to hashset and increase counter by 1.

Upvotes: 1

Guillaume
Guillaume

Reputation: 14656

You can replace most of this code by this one line:

int count = a.chars().distinct().count();

This transforms you string input into a stream of characters, gets the distinct values and returns the count.

Upvotes: 3

Related Questions