Created
May 31, 2018 20:56
-
-
Save Jakemangan/1e2cb45affa35a1722a991b803a28832 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
class Challenge { | |
private static char[] chars; | |
private static int indexOfFirstNonRepeat; | |
/* | |
* @Param String input - String to be tested for first repeated character | |
* @Return String firstNonRepeatSensitive - String containing single character that represents first | |
* non-repeated character in input string (case-sensitive) | |
*/ | |
public static String firstNonRepeatingLetter(String input) | |
{ | |
//Init values | |
chars = null; | |
indexOfFirstNonRepeat = 0; | |
System.out.println("Input string: " + input); | |
//Create case-sensitive and case-insensitive versions of input | |
String inputSensitive = input; | |
String inputInsensitive = input.toLowerCase(); | |
System.out.println("String used for comparison: " + inputInsensitive); | |
//Check if all characters in string are repeated, if not, proceed. | |
if(checkAllRepeated(inputInsensitive)) | |
{ | |
System.out.println("String contains all repeated characters"); | |
return ""; | |
} | |
else | |
{ | |
//Convert insensitive string into char array for comparison | |
chars = inputInsensitive.toCharArray(); | |
char firstNonRepeat = '\0'; | |
//For all chars in array | |
for(char c : chars) | |
{ | |
//Check if index of current char is equal to index of last char | |
if(inputInsensitive.indexOf(c) == inputInsensitive.lastIndexOf(c)) | |
{ | |
//Set value of first non repeated char | |
firstNonRepeat = c; | |
System.out.println("First none repeat (case-insensitive): " + c); | |
//Set index of first non repeated char | |
indexOfFirstNonRepeat = inputInsensitive.indexOf(c); | |
System.out.println("Index of first none repeat: " + indexOfFirstNonRepeat); | |
break; | |
} | |
} | |
System.out.println("Sensitive string: " + inputSensitive); | |
//Use index of case-insensitive repeated char to find case-sensitive char | |
char firstNonRepeatSensitive = inputSensitive.charAt(indexOfFirstNonRepeat); | |
System.out.println("First none repeated char (case-sensitive): " + firstNonRepeatSensitive); | |
return Character.toString(firstNonRepeatSensitive); | |
} | |
} | |
/* | |
* Check if all characters in string are repeated | |
* @Param String input - input string to be tested | |
* @Return boolean | |
*/ | |
public static boolean checkAllRepeated(String input) | |
{ | |
char[] chars = input.toCharArray(); | |
if(chars.length == 1) | |
{ | |
return false; | |
} | |
int n = input.length(); | |
for (int i = 1; i < n; i++) | |
if (chars[i] != chars[0]) | |
return false; | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment