Vowels in a string, patterns Checking if all five vowels are present in a string.

String phrase = "Hello, how are you keeping?";
String vowelsInPhrase = phrase.toLowerCase().replaceAll("[^aeiou]", "");
String temp = vowelsInPhrase;
String usedVowels = "";
    while(temp.length() &gt; 0){
        usedVowels += temp.substring(0, 1);
        temp = temp.replaceAll(temp.substring(0, 1), "");
    }
    if(usedVowels.length() == 5){
        result += "At least one occurrence of each vowel.\n";
    }


Does anyone have a better solution?? I am thinking some sort of pattern to check if each required character has appeared one or more times but I don't know if it is possible. This would save using the while loop.

Something like this is what I was thinking:

String pattern = "[[a]+[e]+[i]+[o]+[u]+]";
if(usedVowels.matches(pattern){
        result += "At least one occurrence of each vowel.\n";
    }
Any solution to this would have to be at least O(n), because worst case you're going to have to check every character in the String.

A very simple solution to this problem is to create an array of 5 booleans, corresponding to the 5 vowels. Then iterate through the string, and if you see a vowel, mark that index (e.g. a = 0, e = 1, etc.) as true. As soon as all 5 are true, return true, as all the vowels occur (assuming that you don't care if they occur more than once).

That has the same time complexity as your regex solution and is far simpler to implement/read/maintain.

You could also sort the string and then binary search for each of the required characters. This has a higher upfront cost (nlogn for the sort, logn for each binary search), but if you're making multiple queries on the same string, might be more efficient in the long run.