Given a string s consisting of lowercase Latin Letters, find the first non repeating character in s.
Input:
The first line contains T denoting the number of testcases. Then follows description of testcases. Each case begins with a single integer N denoting the length of string. The next line contains the string s.
Output:
For each testcase, print the first non repeating character present in string. Print -1 if there is no non repeating character.
Constraints:
1<=T<=50 1<=N<=100
Example:
Input :
3 5 hello 12 zxvczbtxyzvy 6 xxyyzz
Output :
h c -1
My approach:
/*package whatever //do not write package name here */
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.*;
class GFG {
private static int firstNonRepNum (String str, int size)
{
Hashtable <Character, Integer> count = new Hashtable<>();
int occurs;
for (char ch: str.toCharArray())
{
if (!count.containsKey(ch))
{
count.put(ch,1);
}
else
{
occurs = count.get(ch);
count.put(ch, occurs+1);
}
}
for (char ch: str.toCharArray())
{
int val = count.get(ch);
if (val == 1)
{
return ch;
}
}
return -1;
}
public static void main (String[] args) throws IOException{
//code
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//String line = br.readLine();
Scanner sc = new Scanner(System.in);
int numTests = sc.nextInt();
String line2;
int size;
String str;
for (int i = 0; i < numTests; i++)
{
size = sc.nextInt();
str = sc.next();
if (firstNonRepNum(str,size) == -1)
{
System.out.println("-1");
}
else
{
System.out.println((char)firstNonRepNum(str, size));
}
}
}
}
I have the following questions with regards to the above code:
How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?