I've been trying out the new section on codingbat, map1 & 2. I've finished map1, and I'm halfway through map2 but I'm just stuck on this one problem. I can't seem to figure out how to combine two strings.
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.
Examples:
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([]) → {}
Here's my code:
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;
}
I only get {"d": "d", "b": "", "c": "", "a": ""}
I've also tried s.substring(0, 1, map.get(s) + map.get(s))
which only returns null
. If anyone could explain this to me it would be greatly appreciated!
Thank you !