LeetCode Find Words That Can Be Formed by Characters Solution Explained - Java

preview_player
Показать описание


Preparing For Your Coding Interviews? Use These Resources
————————————————————

Other Social Media
----------------------------------------------

Show Support
------------------------------------------------------------------------------

#coding #programming #softwareengineering
Рекомендации по теме
Комментарии
Автор

Your style of deliver the enlightenment coding wisdom is Thespian level
Thankyou

diwakarsharma
Автор

This is my solution in Python:

def find_words_with_chars(words, chars):
if len(words)==0 or len(chars)==0:
return 0
max_count = 0
for word in words:
tmp_chars = copy.deepcopy(chars)
tmp_chars = list(tmp_chars)
cnt = 0
for char in word:
if char in tmp_chars:
idx = tmp_chars.index(char)
tmp_chars[idx] = ''
cnt += 1
else:
cnt = 0
break
max_count += cnt
return max_count

jugsma
Автор

thanks man! really helpful, can you help with medium level questions because the problem lies in the medium ones

amanjakhar
Автор

similar approach using array list
class Solution {
public int countCharacters(String[] words, String chars) {
int count=0;
ArrayList<Character>list =new ArrayList<>();
for(int i=0;i<chars.length();i++)
{
list.add(chars.charAt(i));
}

for(int i=0;i<words.length;i++)
{
String s=words[i];
int k=0;
List<Character> cloned_list
= new ArrayList<Character>();
cloned_list.addAll(list);
for(int j=0;j<s.length();j++)
{


{

k++;

}

}

if(k==s.length())
{
count =count+s.length();
}

}

return count;

}
}

harshnist
Автор

thanks man, this is helpful, but your hand clapping killed my earbuds.

egorshalnev
Автор

class Solution {
public int countCharacters(String[] words, String chars) {
int result = 0;
HashMap<Character, Integer> mymap = new HashMap<>();

for (char c : chars.toCharArray()) {
mymap.put(c, mymap.getOrDefault(c, 0) + 1);
}

for (String word : words) {
// Create a copy of the original frequency map for each word

if (canbeformed(word, new HashMap<Character, Integer>(mymap))) {
result += word.length();
}
}

return result;
}

private boolean canbeformed(String word, Map<Character, Integer> copymap) {
for (char ch : word.toCharArray()) {
if (!copymap.containsKey(ch) || copymap.get(ch) < 1) {
return false;
}
copymap.put(ch, copymap.get(ch) - 1);
}
return true;
}
}

unknownman