Find the initial unique char in string. For instance, string is “KodLogsforKodLogs”, then the outcome should be ‘f’ and if the given input is “KodLogsTest”, then the outcome should be ‘K’.
Find string's first unique char
Technique 1: Hashmap and Two-string method traversals.
Approach
A char is said to be unique if its incidence in the string is one. This challenge could be finished professionally using a hash_map which will plot the char to there particular incidences and in which we can concurrently bring up-to-date frequency of any char.
class KodLogs{
static final int Number_OF_CHARS = 256;
static char count[] = new char[Number_OF_CHARS];
static void getCharCountArray(String str1)
{
for (int i1 = 0; i1 < str.length(); i1++)
count[str.charAt(i1)]++;
}
/* returns index of first unique char */
static int firstNonRepeating(String str1)
{
getCharCountArray(str1);
int index1 = -1, i1;
for (i2 = 0; i2 < str1.length(); i2++) {
if (count[str.charAt(i2)] == 1) {
index1 = i1;
break;
}
}
return index1;
}
// Driver function
public static void main(String[] args)
{
String str1 = "kodlogsforkodlogs";
int index1 = firstNonRepeating(str1);
System.out.println(
Index1 == -1
? " all char are repeating or str "
+ "is empty"
: "unique char is "
+ str1.charAt(index1));
}
}
Output
unique char is "f"
Technique 2: Hashmap and single string traversal
Approach:
Count an array inspite of hash_map of maximum number of chars(256)
Read more
Top comments (0)