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.

  • 相关阅读:
    bzoj4195 [Noi2015]程序自动分析
    bzoj4236 JOIOJI hash 模拟
    bzoj1012 [JSOI2008]最大数maxnumber
    day 4 名片管理系统 -函数版
    day 3 局部变量 全局变量
    day 2 函数的嵌套
    day1 函数 (独立功能代码块)
    day 14 元组
    day 13 字典dict 操作
    day 12 列表字典 补充
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5211776.html
Copyright © 2011-2022 走看看