zoukankan      html  css  js  c++  java
  • Group Shifted Strings -- LeetCode

    Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:

    "abc" -> "bcd" -> ... -> "xyz"

    Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.

    For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
    A solution is:

    [
      ["abc","bcd","xyz"],
      ["az","ba"],
      ["acef"],
      ["a","z"]
    ]
     1 class Solution {
     2 public:
     3     string help(string word) {
     4         for (int i = 1, n = word.size(); i < n; i++) {
     5             word[i] = word[i] - word[0] + 'a';
     6             while (word[i] < 'a') word[i] += 26;
     7         }
     8         word[0] = 'a';
     9         return word;
    10     }
    11     vector<vector<string>> groupStrings(vector<string>& strings) {
    12         unordered_map<string, int> dict;
    13         vector<vector<string> > res;
    14         for (int i = 0, n = strings.size(); i < n; i++) {
    15             string base = help(strings[i]);
    16             if (dict.count(base) == 0) {
    17                 dict.insert(make_pair(base, res.size()));
    18                 vector<string> subGroup(1, strings[i]);
    19                 res.push_back(subGroup);
    20             }
    21             else res[dict[base]].push_back(strings[i]);
    22         }
    23         return res;
    24     }
    25 };
  • 相关阅读:
    Centos7 ifconfig命令找不到
    request的各种方法
    linux开放端口
    easyui datagrid 部分参数
    设置tomcat内存
    tomcat做成系统服务
    Meta-analysis with complex research designs: dealing with dependence from multiple measures and multiple group comparisons
    多重校正
    DTI
    learning source archive
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5769925.html
Copyright © 2011-2022 走看看