Skip to content

Add test cases for isAllCharactersUniqueAndInASCII() #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 27, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Change method name and enhance code
  • Loading branch information
DatMV01 committed Jul 27, 2024
commit 240acbb59335efce1d766d64b987a35ba2807bb5
37 changes: 27 additions & 10 deletions src/main/java/com/ctci/arraysandstrings/IsUnique.java
Original file line number Diff line number Diff line change
@@ -6,16 +6,33 @@
*/
public class IsUnique {

private static boolean hasAllUniqueCharacters(String str) {
if (str == null || str.length() > 128) return false;
/**
* Check whether the input string contains different individual characters and it in the ASCII table.
*
* @param str Input string
* @return true if all characters are different from each other, otherwise false.
*/
public static boolean isAllCharactersUniqueAndInASCII(String str) {
if (str == null || str.isEmpty()) {
return false;
}

int maxCharIndex = 128;
int stringLength = str.length();

boolean[] charSet = new boolean[128]; // assuming the string contains only ASCII characters
for (int i = 0; i < str.length(); i++) {
int charVal = str.charAt(i);
if (charSet[charVal]) {
if (stringLength > maxCharIndex) {
return false;
}

boolean[] characterTrack = new boolean[maxCharIndex]; // assuming the string contains only ASCII characters
for (int i = 0; i < stringLength; i++) {
int charIndex = str.charAt(i);
if (charIndex >= maxCharIndex
|| characterTrack[charIndex]) {
return false;
}
charSet[charVal] = true;

characterTrack[charIndex] = true;
}
return true;
}
@@ -34,11 +51,11 @@ private static boolean hasAllUniqueCharactersWhenStringContainsAllLowercase(Stri

public static void main(String[] args) {
String s = "ram";
System.out.println(hasAllUniqueCharacters(s));
System.out.println(isAllCharactersUniqueAndInASCII(s));
s = "rama";
System.out.println(hasAllUniqueCharacters(s));
System.out.println(isAllCharactersUniqueAndInASCII(s));
s = "ramA";
System.out.println(hasAllUniqueCharacters(s));
System.out.println(isAllCharactersUniqueAndInASCII(s));
System.out.println("-------");
s = "ram";
System.out.println(hasAllUniqueCharactersWhenStringContainsAllLowercase(s));