Last active
May 12, 2020 17:13
-
-
Save thiagotn/a83b73abb62516219a75a65256027aa8 to your computer and use it in GitHub Desktop.
This file contains 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
import java.util.Scanner; | |
/* | |
Problem: | |
https://www.hackerrank.com/contests/dstest-1/challenges/character-game | |
*/ | |
public class Solution { | |
private static final Scanner scanner = new Scanner(System.in); | |
public static void main(String[] args) { | |
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ | |
int cases = scanner.nextInt(); | |
int count = 0; | |
while (scanner.hasNextLine() && count < cases) { | |
String currentString = scanner.nextLine(); | |
if (currentString.isEmpty()) continue; | |
int position = findFirstNonRepeatingCharacter3(currentString); | |
if (position < 0) { | |
System.out.println(position); | |
} else { | |
System.out.println(currentString.charAt(position)); | |
} | |
count++; | |
} | |
scanner.close(); | |
} | |
private static int firstNoRepeatingCharacter(String word) { | |
if (word == null || word.isEmpty()) return -1; | |
if (word.length() > 300) return -1; | |
int nonRepeatedCharPosition = -1; | |
for (int i = 0; i < word.length(); i++) { | |
char current = word.charAt(i); | |
if (word.indexOf(current) == word.lastIndexOf(current)) { | |
nonRepeatedCharPosition = i; | |
break; | |
} | |
} | |
return nonRepeatedCharPosition; | |
} | |
private static int findFirstNonRepeatingCharacter2(String word) { | |
int[] char_counts = new int[26]; | |
// fill array with all chars contained in 'word' | |
// and incrementing each item with amount of occurrences | |
for (char c : word.toCharArray()) { | |
char_counts[c - 'a']++; | |
} | |
// for each item and return the first with size 1 | |
for (char c : word.toCharArray()) { | |
int actual = c - 'a'; | |
if (char_counts[actual] == 1) { | |
return word.indexOf(c); | |
} | |
} | |
return -1; | |
} | |
private static int findFirstNonRepeatingCharacter3(String word) { | |
int[] char_counts = new int[255]; | |
// fill array with all chars contained in 'word' | |
// and incrementing each item with amount of occurrences | |
for (char c : word.toCharArray()){ | |
int numericValue = (int) c; | |
System.out.println("char: " + c + " - " + numericValue); | |
char_counts[numericValue]++; | |
} | |
// for each item and return the first with size 1 | |
for (char c : word.toCharArray()) { | |
int numericValue = (int) c; | |
if (char_counts[numericValue] == 1) { | |
return word.indexOf(c); | |
} | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment