6
6
*/
7
7
public class IsUnique {
8
8
9
- private static boolean hasAllUniqueCharacters (String str ) {
10
- if (str == null || str .length () > 128 ) return false ;
9
+ /**
10
+ * Check whether the input string contains different individual characters and it in the ASCII table.
11
+ *
12
+ * @param str Input string
13
+ * @return true if all characters are different from each other, otherwise false.
14
+ */
15
+ public static boolean isAllCharactersUniqueAndInASCII (String str ) {
16
+ if (str == null || str .isEmpty ()) {
17
+ return false ;
18
+ }
19
+
20
+ int maxCharIndex = 128 ;
21
+ int stringLength = str .length ();
11
22
12
- boolean [] charSet = new boolean [128 ]; // assuming the string contains only ASCII characters
13
- for (int i = 0 ; i < str .length (); i ++) {
14
- int charVal = str .charAt (i );
15
- if (charSet [charVal ]) {
23
+ if (stringLength > maxCharIndex ) {
24
+ return false ;
25
+ }
26
+
27
+ boolean [] characterTrack = new boolean [maxCharIndex ]; // assuming the string contains only ASCII characters
28
+ for (int i = 0 ; i < stringLength ; i ++) {
29
+ int charIndex = str .charAt (i );
30
+ if (charIndex >= maxCharIndex
31
+ || characterTrack [charIndex ]) {
16
32
return false ;
17
33
}
18
- charSet [charVal ] = true ;
34
+
35
+ characterTrack [charIndex ] = true ;
19
36
}
20
37
return true ;
21
38
}
@@ -34,11 +51,11 @@ private static boolean hasAllUniqueCharactersWhenStringContainsAllLowercase(Stri
34
51
35
52
public static void main (String [] args ) {
36
53
String s = "ram" ;
37
- System .out .println (hasAllUniqueCharacters (s ));
54
+ System .out .println (isAllCharactersUniqueAndInASCII (s ));
38
55
s = "rama" ;
39
- System .out .println (hasAllUniqueCharacters (s ));
56
+ System .out .println (isAllCharactersUniqueAndInASCII (s ));
40
57
s = "ramA" ;
41
- System .out .println (hasAllUniqueCharacters (s ));
58
+ System .out .println (isAllCharactersUniqueAndInASCII (s ));
42
59
System .out .println ("-------" );
43
60
s = "ram" ;
44
61
System .out .println (hasAllUniqueCharactersWhenStringContainsAllLowercase (s ));
0 commit comments