Last active
May 8, 2022 10:31
-
-
Save nayyaung/6e372c6abcc032283a7b49d0e0e1127e to your computer and use it in GitHub Desktop.
Temp algo test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.util.Arrays; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class AnagramWithAlternateVowel_1 { | |
private HashMap<Character, Integer> vowels ; | |
private HashMap<Character, Integer> consonents ; | |
private int result = 0; | |
private boolean isVowel(Character c) { | |
return Arrays.asList('A', 'E', 'I', 'O', 'U').contains(c); | |
} | |
private void backtrack(StringBuilder sb, int len){ | |
if(sb.length() == len) { | |
System.out.println(sb); | |
result++; | |
return; | |
} | |
if (sb.length() >= 1 && !isVowel(sb.charAt(sb.length() -1 ))) { | |
for(Map.Entry<Character, Integer> kv : vowels.entrySet()) { | |
if (kv.getValue() == 0) { | |
continue; | |
} | |
int tmpCount = kv.getValue(); | |
vowels.put(kv.getKey(), kv.getValue() - 1); | |
sb.append(kv.getKey()); | |
backtrack(sb, len); | |
sb.deleteCharAt(sb.length() - 1); | |
vowels.put(kv.getKey(), tmpCount); | |
} | |
} | |
else { | |
for(Map.Entry<Character, Integer> kv : consonents.entrySet()) { | |
if (kv.getValue() == 0) { | |
continue; | |
} | |
int tmpCount = kv.getValue(); | |
consonents.put(kv.getKey(), kv.getValue() - 1); | |
sb.append(kv.getKey()); | |
backtrack(sb, len); | |
sb.deleteCharAt(sb.length() - 1); | |
consonents.put(kv.getKey(), tmpCount); | |
} | |
} | |
} | |
public int getCount(String s) { | |
vowels = new HashMap<>(); | |
consonents = new HashMap<>(); | |
result = 0; | |
int vCount = 0; | |
int cCount = 0; | |
for(int i =0 ; i < s.length(); i++) { | |
Character c = s.charAt(i); | |
if (isVowel(c)) { | |
vowels.put(c, vowels.getOrDefault(c, 0) + 1); | |
vCount++; | |
}else { | |
consonents.put(c,consonents.getOrDefault(c, 0) + 1); | |
cCount++; | |
} | |
} | |
if (cCount != vCount && cCount != vCount +1) {return 0;} | |
backtrack(new StringBuilder(), s.length()); | |
return result; | |
} | |
public static void main(String[] args) { | |
var t = new AnagramWithAlternateVowel_1(); | |
var res = t.getCount("GADO"); | |
System.out.println(res); | |
res = t.getCount("AABCY"); | |
System.out.println(res); | |
res = t.getCount("XAABCY"); | |
System.out.println(res); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment