Saturday, July 31, 2021

Java First non repeating character in a string

Let's say we have string "afgfgfdfayd" in this if you see character 'y' is non - repeating char and also first and only.

To identify first non - repeating we will pick first char and compare with each char if found repeating will put this in a list and will pick second char and repeat the same process. After complete the process for each element we will check the last char we left with and if this char not into duplicate list we found and if exist into list then every char is duplicate (repeating).

public class FNonRepet {

public static void main(String[] args) {

String s = "afgfgfdfayd";

char ar[] = s.toCharArray();

List<Character> l = new ArrayList<>();

int k = 0;

int i = 1;

char charact = ar[k];

while (i < ar.length) {

if (l != null && l.contains(charact)) {

charact = ar[++k];

i = k + 1;

continue;

} else if ((charact == ar[i])) {

l.add(charact);

charact = ar[++k];

i = k + 1;

continue;

}

i++;

}

if (!l.contains(charact)) {

System.out.println("Character '"+ charact+ "' is first non repetative" );

}else {

System.out.println("Every char is repetative" );

}

}

}

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home