I've got a 6 char long string, and I would like to check, if there is just one from each character. How to?
Asked
Active
Viewed 80 times
-6
-
2Please give example input and code you are trying – OneCricketeer May 20 '17 at 19:03
-
More expansive explanation for working with strings you can have here: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java and https://www.tutorialspoint.com/java/java_strings.htm and https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html – Vasyl Lyashkevych May 20 '17 at 19:20
2 Answers
3
You could compare the number of distinct characters to the length of the string:
boolean charMoreThanOnce = s.chars().distinct().count() < s.length();

Mureinik
- 297,002
- 52
- 306
- 350
-
1As much as I like such nice, clean, precise answers; I still feel tempted to not upvote; as this very much looks like you just did somebody's homework. Not that he will be able to make much out of this, but still. – GhostCat May 20 '17 at 19:08
-
1Is it splitting hairs to point out that [it doesn't work for `""`](http://ideone.com/dyN8ym)? – Andy Turner May 20 '17 at 19:11
0
You can do it using a Set
. You need unique elements and Set
gurantees you containing the unique elements. HashSet
is implementation of Set
, you can use it to implement this idea.
public boolean ifAllCharsUnique(String input){
char[] arr = input.toCharArray();
int length = arr.length;
Set<Character> checker = new HashSet<>();
for(int i =0 ; i < length; i++){
if(checker.contains(arr[i]){
return false;
}
checker.add(arr[i]);
}
return true;
}

nits.kk
- 5,204
- 4
- 33
- 55
-
With this method, I create a new array (or ArrayList ? ) < checker > , which only contains unique characters? – jaraipali May 20 '17 at 19:51