A string is said to be complete if it contains all the characters from a to z. Given a string, check if it complete or not. e.g.
Sample Input
3 wyyga qwertyuioplkjhgfdsazxcvbnm ejuxggfsts
Sample Output
NO YES NO
Solution using for loop and indexOf()
I wrote a quick function which is able to find this complete string.
package com.howtodoinjava.examples; public class CheckAllAlphabetsAlgorithms { public static void main(String[] args) { System.out.println( checkAllChars( "qwertyuioplkjhgfdsAzxcvbnm" ) ); System.out.println( checkAllChars( "123" ) ); System.out.println( checkAllChars( "ejuxggfsts" ) ); System.out.println( checkAllChars( "wyyga" ) ); } private static String checkAllChars ( String input ) { //If input length is less than 26 then it can never be complete if(input.length() < 26) { return "FALSE"; } for (char ch = 'A'; ch <= 'Z'; ch++) { if (input.indexOf(ch) < 0 && input.indexOf((char) (ch + 32)) < 0) { return "FALSE"; } } return "TRUE"; } }
Output:
TRUE FALSE FALSE FALSE
Solution using for regular expressions
Here is a (ugly because I don’t like long regex) solution to find complete string using regex.
package com.howtodoinjava.examples; public class CheckAllAlphabetsAlgorithms { public static void main(String[] args) { System.out.println( checkAllCharsUsingRegex( "qwertyuioplkjhgfdsAzxcvbnm" ) ); System.out.println( checkAllCharsUsingRegex( "123" ) ); System.out.println( checkAllCharsUsingRegex( "ejuxggfsts" ) ); System.out.println( checkAllCharsUsingRegex( "wyyga" ) ); } private static String checkAllCharsUsingRegex ( String input ) { //If input length is less than 26 then it can never be complete if(input.length() < 26) { return "FALSE"; } String regex = "(?i)(?=.*a)(?=.*b)(?=.*c)(?=.*d)(?=.*e)(?=.*f)" + "(?=.*g)(?=.*h)(?=.*i)(?=.*j)(?=.*k)(?=.*l)(?=.*m)(?=.*n)" + "(?=.*o)(?=.*p)(?=.*q)(?=.*r)(?=.*s)(?=.*t)(?=.*u)(?=.*v)" + "(?=.*w)(?=.*x)(?=.*y)(?=.*z).*"; if(input.matches(regex)){ return "TRUE"; } return "FALSE"; } }
Output:
TRUE FALSE FALSE FALSE
Happy Learning !!
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Here is a hardcore way! =)
O(N) time and O(N) space:
boolean check1(String str) {
int bits = 0;
for (char c : str.toCharArray()) {
bits |= 1 << c – 'a';
if (bits == (1 < bits[0] |= 1 < bits[0] == (1 << 'z' – 'a' + 1) – 1);
}
Looks like part of my comment was missed, here is even better solution that avoids copying array and so we have O(N) time and O(1) space, but it does bad thing in terms of clear code – changes external state during stream processing
boolean check2(String str) {
int[] bits = {0};
return str.chars()
.map(c -> bits[0] |= 1 < bits[0] == (1 << 'z' – 'a' + 1) – 1);
}
Your offered solutions are both O(N^2) and O(1) space. By using a HashMap, you can get O(N) performance and O(N) space