Loop over the given array of strings to build a result string like this: when a string appears the 2nd, 4th, 6th, etc. time in the array, append the string to the result. Return the empty string if no string appears a 2nd time.
wordAppend(["a", "b", "a"]) → "a"
wordAppend(["a", "b", "a", "c", "a", "d", "a"]) → "aa"
wordAppend(["a", "", "a"]) → "a"
Loop over the given array of strings to build a result string like this: when a string appears the 2nd, 4th, 6th, etc. time in the array, append the string to the result. Return the empty string if no string appears a 2nd time.
public String wordAppend(String[] strings) {
// public Map<String, Integer> wordCount(String[] strings) {
Map<String, Integer> map=new TreeMap();
String result="";
for(int i=0;i<strings.length;i++){
// String buffer=strings[i]
String test=strings[i];
if(map.containsKey(test)){
int count=map.get(test);
map.put(test,count+1);
}
else{
map.put(test,1);
}
result= map.keySet();
}
return result;
}
is it like return (number of times a found divided by 2 )number of times of a??That's what I said, yes.
what it mean by appears at 4th 6th etc??bit confusing descriptionA 2nd, 4th, 6th occurrence of the string "a"
Map<String, Integer> map=new TreeMap();
Do you have a good reason for using a TreeMap?
public String wordAppend(String[] strings) {
Map<String, Integer> test = new HashMap<String, Integer>();
String res= "";
for (int i = 0; i < strings.length; i++) {
String key = strings[i];
if (test.containsKey(key)) {
int val = test.get(key);
val++;
if (val % 2 == 0) {
res = res+key;
}
test.put(key, val);
} else {
test.put(key, 1);
}
}
return res;
}