Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 240acbb

Browse files
committed
Change method name and enhance code
1 parent e2af922 commit 240acbb

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

src/main/java/com/ctci/arraysandstrings/IsUnique.java

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,33 @@
66
*/
77
public class IsUnique {
88

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();
1122

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]) {
1632
return false;
1733
}
18-
charSet[charVal] = true;
34+
35+
characterTrack[charIndex] = true;
1936
}
2037
return true;
2138
}
@@ -34,11 +51,11 @@ private static boolean hasAllUniqueCharactersWhenStringContainsAllLowercase(Stri
3451

3552
public static void main(String[] args) {
3653
String s = "ram";
37-
System.out.println(hasAllUniqueCharacters(s));
54+
System.out.println(isAllCharactersUniqueAndInASCII(s));
3855
s = "rama";
39-
System.out.println(hasAllUniqueCharacters(s));
56+
System.out.println(isAllCharactersUniqueAndInASCII(s));
4057
s = "ramA";
41-
System.out.println(hasAllUniqueCharacters(s));
58+
System.out.println(isAllCharactersUniqueAndInASCII(s));
4259
System.out.println("-------");
4360
s = "ram";
4461
System.out.println(hasAllUniqueCharactersWhenStringContainsAllLowercase(s));

0 commit comments

Comments
 (0)