zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Anagrams

    Anagrams 

    Given an array of strings, return all groups of strings that are anagrams.

    Note: All inputs will be in lower-case.

    https://leetcode.com/problems/anagrams/


     
     
     
    主要是不理解题目的意思啊,也没有例子。
    anagrams就是由颠倒字母顺序而构成的字。
    要求找出给定数组中所有的anagrams,注意到可能有多组。
    比如:
    ["tea","and","ate","eat","den"] --> ["tea","ate","eat"]
    ["tea","and","ate","eat","dan"] --> ["tea","ate","eat","and","dan"]
     
    哈希表+字符串排序。
    每个进来的string,都按照字母大小排个序,作为特征塞进哈希表。
    如果第一次碰到这个特征string,塞两个进结果数组,之后碰到只要塞当前的string进结果数组。
    javascript String对象貌似没有排序的方法吧...强行拆成数组排完序再join起来。
     
     1 /**
     2  * @param {string[]} strs
     3  * @return {string[]}
     4  */
     5 var anagrams = function(strs) {
     6     var result = [], dict = {}, tmp;
     7     for(var i = 0; i < strs.length; i++){
     8         tmp = sortStr(strs[i]);
     9         if(dict[tmp] === undefined){
    10             dict[tmp] = strs[i];
    11         }else{
    12             if(result.indexOf(dict[tmp]) === -1){
    13                 result.push(dict[tmp]);
    14             }
    15             result.push(strs[i]);
    16         }
    17     }
    18     return result;
    19 
    20     function sortStr(str){
    21         var tmp = str.split('');
    22         tmp.sort(sorting);
    23         return tmp.join('');
    24     }
    25 
    26     function sorting(a, b){
    27         if(a > b){
    28             return 1;
    29         }else if(a < b){
    30             return -1;
    31         }else{
    32             return 0;
    33         }
    34     }
    35 };
     
     
     
  • 相关阅读:
    Mysql备份恢复
    Mysql事务学习笔记
    MongoDB进阶
    MongoDB入门
    Mysql流程解析
    Mysql Explain学习笔记
    面试题
    聚集索引和非聚集索引
    端口号占用
    classpath: 和classpath*:的区别
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4696213.html
Copyright © 2011-2022 走看看