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

Commit 4356d80

Browse files
committed
Change method name and enhance code
1 parent a051a1a commit 4356d80

File tree

1 file changed

+31
-8
lines changed

1 file changed

+31
-8
lines changed

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

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,37 @@ public static boolean isAllCharactersUniqueAndInASCII(String str) {
3737
return true;
3838
}
3939

40-
private static boolean hasAllUniqueCharactersWhenStringContainsAllLowercase(String s) {
40+
/**
41+
* Check whether the input string contains different individual characters, lowercase
42+
* and in between 'a' and 'z'
43+
*
44+
* @param str Input string
45+
* @return true if all characters are different from each other,lowercase and between 'a' and 'z', otherwise false.
46+
*/
47+
public static boolean isAllCharactersUniqueAndLowercaseAndInAlphabet(String str) {
48+
if (str == null
49+
|| str.isEmpty()
50+
|| str.length() > 26) {
51+
return false;
52+
}
53+
4154
int checker = 0;
42-
for (int i = 0; i < s.length(); i++) {
43-
int charValue = s.charAt(i) - 'a';
44-
if ((checker & (1 << charValue)) > 0) {
55+
int stringLength = str.length();
56+
for (int i = 0; i < stringLength; i++) {
57+
58+
char character = str.charAt(i);
59+
if (!(character >= 'a' && character <= 'z')) {
4560
return false;
4661
}
47-
checker |= (1 << charValue);
62+
63+
int characterIndex = character - 'a';
64+
int singleBitOnPosition = 1 << characterIndex ;
65+
66+
if ((checker & singleBitOnPosition) > 0) {
67+
return false;
68+
}
69+
70+
checker |= singleBitOnPosition; // checker = checker | singleBitOnPosition;
4871
}
4972
return true;
5073
}
@@ -58,11 +81,11 @@ public static void main(String[] args) {
5881
System.out.println(isAllCharactersUniqueAndInASCII(s));
5982
System.out.println("-------");
6083
s = "ram";
61-
System.out.println(hasAllUniqueCharactersWhenStringContainsAllLowercase(s));
84+
System.out.println(isAllCharactersUniqueAndLowercaseAndInAlphabet(s));
6285
s = "rama";
63-
System.out.println(hasAllUniqueCharactersWhenStringContainsAllLowercase(s));
86+
System.out.println(isAllCharactersUniqueAndLowercaseAndInAlphabet(s));
6487
// not working as the input contains different cases
6588
s = "ramA";
66-
System.out.println(hasAllUniqueCharactersWhenStringContainsAllLowercase(s));
89+
System.out.println(isAllCharactersUniqueAndLowercaseAndInAlphabet(s));
6790
}
6891
}

0 commit comments

Comments
 (0)