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

    原题链接在这里:https://leetcode.com/problems/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"]
    ]

    题解:

    维护一个HashMap, key是每个string 的 base型.

    Note: char c, c - diff, need cast.

    Time Complexity: O(nm), n = strings.length. m = average length of strings.

    Space: O(hm.size()), HashMap size.

    AC Java:

     1 class Solution {
     2     public List<List<String>> groupStrings(String[] strings) {
     3         List<List<String>> res = new ArrayList<>();
     4         if(strings == null || strings.length == 0){
     5             return res;
     6         }
     7         
     8         Map<String, List<String>> hm = new HashMap<>();
     9         for(String s : strings){
    10             String base = getBase(s);
    11             hm.putIfAbsent(base, new ArrayList<String>());
    12             hm.get(base).add(s);
    13         }
    14         
    15         return new ArrayList<List<String>>(hm.values());
    16     }
    17     
    18     private String getBase(String s){
    19         if(s == null || s.length() == 0){
    20             return s;
    21         }
    22         
    23         char [] arr = s.toCharArray();
    24         int diff = arr[0] - 'a';
    25         for(int i = 0; i<arr.length; i++){
    26             arr[i] = (char)(arr[i]-diff);
    27             if(arr[i] < 'a'){
    28                 arr[i] += 26;
    29             }
    30         }
    31         
    32         return new String(arr);
    33     }
    34 }

    类似Group AnagramsShifting Letters.

  • 相关阅读:
    poj 1860 Currency Exchange(最短路径的应用)
    poj 2965 The Pilots Brothers' refrigerator
    zoj 1827 the game of 31 (有限制的博弈论)
    poj 3295 Tautology (构造法)
    poj 1753 Flip Game(枚举)
    poj 2109 (贪心)
    poj 1328(贪心)
    Qt 对单个控件美化
    Qt 4基础
    Bash Shell
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5211776.html
Copyright © 2011-2022 走看看