How to check, if a word can be made by letters of another word. using every letter only once.
Example:
if str = "computer";
then
//if user enters below words output must be true
comp
put
poet
//and if user enters below words output must be false
count // since n is not in str
root // since there is only single o in str
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
We take the user input as strings. We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.
The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search.
This is a solution based on counting the number of each character and then checking that the second word has fewer of each character:
public static bool UsesSameLetters(string input, string check)
{
var OriginalCounts = input.GroupBy(c => c)
.ToDictionary(g => g.Key, g => g.Count());
bool Success = check.GroupBy(c => c)
.All(originalCounts.ContainsKey(g.Key)
&& originalCounts[g.Key] >= g.Count);
return Success;
}
This solution counts the number of each character in the input string, and then checks if every character in the check string occurs less times than it does in the input string. This solution is fairly declaritive.
The following should do the trick
public static bool UsesSameLetters(string input, string check) {
var array = new BitArray(check.Length, false);
for (var i = 0; i < input.Length; i++) {
var found = false;
for (var j = 0; j < check.Length; j++) {
if (input[i] == check[j] && !array.Get(j)) {
array.Set(j, true);
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With