我一直在尝试关于codingbat、map1和2的新部分。我已经完成了map1,并且我已经完成了map2的一半,但我只是卡在了这个问题上。我似乎不知道如何组合两个字符串。
Given an array of non-empty strings, return a
Map<String, String>
with a key for every different first character seen, with the value of all the strings starting with that character appended together in the order they appear in the array.
示例:
firstChar(["salt", "tea", "soda", "toast"]) → {"t": "teatoast", "s": "saltsoda"}
firstChar(["aa", "bb", "cc", "aAA", "cCC", "d"]) → {"d": "d", "b": "bb", "c": "cccCC", "a": "aaaAA"}
firstChar([]) → {}
这是我的代码:
public Map<String, String> firstChar(String[] strings)
{
Map<String, String> map = new HashMap<String, String>();
String x = "";
for ( String s: strings )
{
if ( s.substring(0,1) == s.substring(0,1))
x += s;
map.put(s.substring(0,1), x);
}
return map;
}
我只得到{"d": "d", "b": "", "c": "", "a": ""}
我也尝试过s.substring(0, 1, map.get(s) + map.get(s))
只返回 null
。如果有人能向我解释这一点,我将不胜感激!
谢谢!
最佳答案
你的逻辑是错误的,你正在将字符串的第一个字符与其本身进行比较。另外,虽然这不是您的问题,但您正在使用 ==
而不是 equals
来比较字符串。 ==
用于比较引用,equals
用于比较逻辑相等。另外,要获取字符串的第一个字符,您只需使用 s.charAt(0) 即可。讽刺的是,如果您这样做了,您就不会遇到此问题,因为 String.charAt
返回一个 char
,它是原始类型,因此可以使用 进行安全比较>==
.
具有各种改进和修复的代码:
public Map<String, String> firstChar(String[] strings) {
Map<String, String> map = new HashMap<>();
for (String s: strings) {
map.merge(String.valueOf(s.charAt(0), s, String::concat);
}
return map;
}
或者 Java 8 之前的版本:
public Map<String, String> firstChar(String[] strings) {
Map<String, String> map = new HashMap<>();
for (String s: strings) {
String key = String.valueOf(s.charAt(0));
String value = map.get(key);
map.put(key, (value == null ? "" : value) + s);
}
return map;
}
关于java - 在 map 中组合两个不同的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38680840/