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

    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"]
    ]

    Analyse: keep the diff between each character in the string. Put the strings with same diff in the same vector.

    Runtime: 6ms

     1 class Solution {
     2 public:
     3     vector<vector<string>> groupStrings(vector<string>& strings) {
     4         unordered_map<string, vector<string> > groups;
     5         for (string s : strings) {
     6             if (s.size() == 1) {
     7                 groups["-"].push_back(s);
     8             } else {
     9                 string tempGap;
    10                 for (int i = 1; i < s.size(); i++) {
    11                     if (s[i] > s[i - 1])
    12                         tempGap += to_string(s[i] - s[i - 1]);
    13                     else
    14                         tempGap += to_string(26 + (s[i] - s[i - 1]));
    15                 }
    16                 groups[tempGap].push_back(s);
    17             }
    18         }
    19         
    20         vector<vector<string> > result;
    21         for (auto ite = groups.begin(); ite != groups.end(); ite++) {
    22             vector<string> tempStrings = ite->second;
    23             result.push_back(vector<string>());
    24             for (auto s : tempStrings) {
    25                 result.back().push_back(s);
    26             }
    27         }
    28         return result;
    29     }
    30 };
  • 相关阅读:
    javascript的严格模式:use strict
    Ionic在线打包IOS平台应用
    安装nodejs6.9x以后,原来在nodejs4.2.x中运行正常的ionic项目出现问题的解决
    cordova插件分类
    ionic 启用sass
    ngCordova
    为Asp.net WebApi 添加跨域支持
    使用ionic framework创建一个简单的APP
    研究主题
    近两天让我羞愧难当的遭遇
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5914982.html
Copyright © 2011-2022 走看看