關于map的使用的一個心得

map的每一個鍵值對里面有一個value值,這一特點可以用來為一個數組里面的每個元素設置一個獨有的不會被其他因素影響的flag。下面用一個例子來說明這個用法:
例子 :給出一個字符串數組,如若此數組中元素為第偶數次出現,則把它拼接到將要返回的結果中;
示例:wordAppend(["a", "b", "b", "b", "a", "c", "a", "a"]) → "baa"
wordAppend(["a", "b", "b", "b", "a", "c", "a", "a", "a", "b", "a"]) → "baaba
wordAppend(["not", "and", "or", "and", "this", "and", "or", "that", "not"]) → "andornot"
在這里如若運用字符串數組遍歷的方法,那么就會面臨很多問題:比如要為每個不同的元素立flag,以得知它是第幾次在數組中出現,這就有點復雜了,因為還要考慮每個元素出現的先后順序不同。而用map的鍵值對的話邏輯一目了然。

  • 用map方法:
    public String wordAppend(String[] strings) {
    Map<String,Inteer>map = new HashMap<String,Integer>();
    String str="";
    int count=1;
    for(int i= 0; i<strings.length; i++){
    if(map.containsKey(strings[i])){
    int value=map.get(strings[i]);
    value++;
    map.put(strings[i],value);
    if( map.get(strings[i])%2==0){
    str+=strings[i];
    }
    }else{
    map.put(strings[i],count);
    }
    }
    return str;
    }

  • 用數組遍歷方法:
    public String wordAppend(String[] strings) {
    Map<String,Integer>map = new HashMap<String,Integer>();
    String str="";
    for(int i= 0; i<strings.length; i++){
    int count=0;
    for(int j=0; j<=i; j++){
    if(strings[i].equals(strings[j])){
    count++;
    }
    }
    if(count%2==0){
    str+=strings[i];
    }
    }
    return str;

    }
    

要問我代碼為什么寫得這么屌?戳下面的鏈接你就知道,想成為碼王一樣的男人嗎?我的代碼都放在那了,想要嗎?還等什么?趕快去拿吧??!

http://qingke.me/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容