• Anagrams


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

    Note: All inputs will be in lower-case.

    思路:

    最开始不理解题意。其实题目的意思是看原数组里面是否有些字符串是互相可以通过改变字母顺序转换的。这样的话使用一个map<string, int>,字符串作为key值,保存下标。遍历原数组,每访问一个字符串,先对它进行排序,看map是否有它,如果有的话,就存入结果vector,否则存入map。注意需要一个标记来记录第一个放入map的字符串是否放入结果,放入之前是字符串的下标,放入后改为-1.

    代码:

     1     vector<string> anagrams(vector<string> &strs) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         vector<string> result;
     5         map<string, int> table;
     6         string tmp;
     7         int n = strs.size();
     8         for(int i = 0; i < n; i++){
     9             tmp = strs[i];
    10             sort(tmp.begin(), tmp.end());
    11             if(table.find(tmp) == table.end()){
    12                 table[tmp] = i;
    13             }
    14             else{
    15                 if(table[tmp] != -1){
    16                     result.push_back(strs[table[tmp]]);
    17                     table[tmp] = -1;
    18                 }
    19                 result.push_back(strs[i]);
    20             }
    21         }
    22         return result;
    23     }
  • 相关阅读:
    获得SQL语句的模板,自己写类似readtrace时候用
    我的HD2手机
    匹配symbols
    再送一次书
    微软急聘MOSS高手!
    邮件规则的实现
    System.Data.SQLClient.SqlConnection在Open之后为什么需要及时Close?
    windbg中无法加载mscorwks.dll, Win32 error 0n2
    Diablo3狗熊榜
    软件构架师的特点
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3418415.html
Copyright © 2020-2023  润新知