这是来自codewars.com的挑战问题。我试图通过使用hashMap来减少重复字符的内部循环访问次数。但是,我的逻辑从某种程度上来说是失败的,你能否请我告诉我哪里搞砸了? 谢谢 以下是挑战说明: 此练习的目标是将字符串转换为新字符串,其中新字符串中的每个字符为'('如果该字符仅在原始字符串中出现一次,或')',如果该字符在原始字符串中出现多次串。在确定字符是否重复时忽略大写。
实施例: “din”=> “(((” --and--“recede”=> “()()()”
public class DuplicateEncoder {
static String encode(String word){
HashMap<Character, Integer> map = new HashMap<>();
int count; //counter for # time character is preset
int i = 0;
String answer = "";
for(int j = 0; j <= word.length() -1; j++)
{
count = 0;
//only allows input if the key is not present in the hashmap
if( !(map.containsKey(word.charAt(j)) ) )
{
// should count the time the character is present.
//there apprears to be a bug in here
for( i = j ; i < word.length() -1 ; i++)
{
if( (word.charAt(j)) == word.charAt(i) ) count++;
}
}
map.put( word.charAt(j), count); //
}
//的System.out.println(map.keySet()); //System.out.println(map.values());
for(i = 0; i <= word.length() -1; i++)
{
if(map.get(word.charAt(i)) <= 1)
{
answer += "(";
}
else{
answer += ")";
}
}
return answer;
}
public static void main(String ...args)
{
System.out.println(encode("recede"));
}
}
答案 0 :(得分:1)
你只需要一个循环(在伪代码中,因为我在手机上打字 - 抱歉):
for (each character in word)
if (character not in map)
map.put(character, 1)
else
map.put(character, map.get(character) +1)
使用此功能,地图将包含每个字符在word
答案 1 :(得分:1)
正如@Hugo建议你不需要内循环。最好将每个字符放在地图中调整出现次数。
此外,您可以使用Java Stream API和java.lang.StringBuilder
来改善代码:
public static String encode(String word) {
final Map<Integer, Integer> map = new HashMap<>();
word.chars().forEach(character -> map.put(character, map.getOrDefault(character, 0) + 1));
final StringBuilder answer = new StringBuilder();
word.chars().forEach(value -> answer.append(map.get(value) > 1 ? ')' : '('));
return answer.toString();
}