Created
December 10, 2019 05:50
-
-
Save AbsolutelySaurabh/aee422a6738d9d30b8f0dc67a2910d5b to your computer and use it in GitHub Desktop.
First non-repeating character in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package practice; | |
import java.util.Scanner; | |
public class Solution1 { | |
//first non-repeating character in a string | |
private static int[] buildFreq(String str){ | |
int freq[] = new int[26]; | |
for(int i = 0; i<26; i++){ | |
freq[i] = 0; | |
} | |
//build freq[] | |
for(int i = 0; i<str.length(); i++){ | |
freq[str.charAt(i) - 'a']++; | |
} | |
return freq; | |
} | |
private static char solve(String str){ | |
int freq[] = new int[26]; | |
freq = buildFreq(str); | |
for(int i = 0; i<26; i++){ | |
if(freq[str.charAt(i) - 'a'] == 1){ | |
return str.charAt(i); | |
} | |
} | |
return ' '; | |
} | |
public static void main(String[] args) { | |
Scanner s = new Scanner(System.in); | |
int test = s.nextInt(); | |
s.nextLine(); | |
while(test > 0){ | |
String str = s.nextLine(); | |
System.out.println(solve(str)); | |
test--; | |
} | |
s.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment