Determine if a string has all unique characters: Difference between revisions
Content added Content deleted
(RPL: add section) |
(New post, showing Java 11 syntax, in addition to existing Java post.) |
||
Line 1,956: | Line 1,956: | ||
XYZ ZYX 7 no 'Z' 5A 3 5 |
XYZ ZYX 7 no 'Z' 5A 3 5 |
||
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ 36 no '0' 30 10 25 |
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ 36 no '0' 30 10 25 |
||
</pre> |
|||
===Using Java 11=== |
|||
<syntaxhighlight lang="java"> |
|||
import java.util.HashSet; |
|||
import java.util.List; |
|||
import java.util.OptionalInt; |
|||
import java.util.Set; |
|||
public final class DetermineUniqueCharacters { |
|||
public static void main(String[] aArgs) { |
|||
List<String> words = List.of( "", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" ); |
|||
for ( String word : words ) { |
|||
Set<Integer> seen = new HashSet<Integer>(); |
|||
OptionalInt first = word.chars().filter( i -> ! seen.add(i) ).findFirst(); |
|||
if ( first.isPresent() ) { |
|||
final char ch = (char) first.getAsInt(); |
|||
final String hex = Integer.toHexString(ch).toUpperCase(); |
|||
System.out.println("Word: \"" + word + "\" contains a repeated character."); |
|||
System.out.println("Character '" + ch + "' (hex " + hex + ") occurs at positions " |
|||
+ word.indexOf(ch) + " and " + word.indexOf(ch, word.indexOf(ch) + 1)); |
|||
} else { |
|||
System.out.println("Word: \"" + word + "\" has all unique characters."); |
|||
} |
|||
System.out.println(); |
|||
} |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{ out }} |
|||
<pre> |
|||
Word: "" has all unique characters. |
|||
Word: "." has all unique characters. |
|||
Word: "abcABC" has all unique characters. |
|||
Word: "XYZ ZYX" contains a repeated character. |
|||
Character 'Z' (hex 5A) occurs at positions 2 and 4 |
|||
Word: "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" contains a repeated character. |
|||
Character '0' (hex 30) occurs at positions 9 and 24 |
|||
</pre> |
</pre> |
||