Reputation: 13
public static void main(String[] args) {
String str = "XXYZZA";
char[] a = str.toCharArray();
int count=0;
for (int i = 0; i < a.length; i++)
{
if (a[i] == a[i++])
{
count++;
}
else
System.out.println(a[i++]);
}
}
the print statement in the "else" part is not being executed. the desired output should be
Y
A
Upvotes: 0
Views: 97
Reputation: 1042
Try like this, may help you
public static void main(String[] args) {
String str = "XXYZZA";
char[] a = str.toCharArray();
HashSet<Character> set = new HashSet<>();
set.add( a[0]);
for (int i = 1; i < a.length; i++)
{
if (!set.contains(a[i]) && (i+1 == a.length || a[i] != a[i+1]))
{
System.out.println(a[i]);
}
set.add(a[i]);
}
Upvotes: 0
Reputation: 605
Ok, first and for-most, proper indentations please, helps out a lot to understand the code.
Secondly, if (a[i] == a[i++])
is not the right way to go because of 2 reasons
a.length - 1
your test condition i++
will try to access the element at index a.length
, which, as you might have guessed it, does not exist.What you need is some sort of sorting algorithm without actually saving the sorted sequence.
Upvotes: 2