-
Notifications
You must be signed in to change notification settings - Fork 1
/
FirstNonRepeatabedCharacter.java
77 lines (68 loc) · 1.92 KB
/
FirstNonRepeatabedCharacter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.javamultiplex.string;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
public class FirstNonRepeatabedCharacter {
public static void main(String[] args) {
Scanner input=null;
try
{
input=new Scanner(System.in);
System.out.println("Enter String: ");
String string=input.next();
char[] stringToChar=string.toCharArray(); //Converting String to char Array.
int orignalLength=stringToChar.length,charCount=0;
String newString=getStringAfterDuplicatesRemoval(stringToChar);
char[] stringToCharAfterDuplicateRemoval=newString.toCharArray(); //Converting String to char Array.
int newLength=stringToCharAfterDuplicateRemoval.length;
boolean repeatedCharacterExist=false;
for(int i=0;i<newLength;i++)
{
charCount=0;
for(int j=0;j<orignalLength;j++)
{
if(stringToCharAfterDuplicateRemoval[i]==stringToChar[j])
{
charCount++;
}
}
if(charCount==1)
{
repeatedCharacterExist=true;
System.out.println("First non repeated character is: "+stringToCharAfterDuplicateRemoval[i]);
break;
}
}
if(!repeatedCharacterExist)
{
System.out.println("All characters are repeated.");
}
}
finally
{
if(input!=null)
{
input.close();
}
}
}
/*
* Removing duplicates by converting char Array to Set.
*/
private static String getStringAfterDuplicatesRemoval(char[] stringToChar) {
HashSet<Character> set=new LinkedHashSet<>();
String result="";
int orignalLength=stringToChar.length;
for(int i=0;i<orignalLength;i++)
{
set.add(stringToChar[i]);
}
Iterator<Character> iterator=set.iterator();
while(iterator.hasNext())
{
result+=iterator.next(); //Converting Set to String
}
return result;
}
}