• Leetcode: 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"], 
    Return:
    
    [
      ["abc","bcd","xyz"],
      ["az","ba"],
      ["acef"],
      ["a","z"]
    ]
    Note: For the return value, each inner list's elements must follow the lexicographic order.

    关键点:group all strings that belong to the same shifting sequence, 所以找到属于相同移位序列的key 很重要。因此单独写了函数shift,

    写这个shift函数,我之前想的很复杂,每个String要移26个距离,看shifted string是不是一个key。其实干嘛这么复杂,指定一个相同移位序列的key,定义为第一个char为‘a’

    buffer.append((c - 'a' - dist + 26) % 26 + 'a') 极容易错。将相同移位序列的Strings存入key 对应的value中,建立正确的HashMap很重要。

     1 public class Solution {
     2     public List<List<String>> groupStrings(String[] strings) {
     3         List<List<String>> res = new ArrayList<List<String>>();
     4         if (strings==null || strings.length==0) return res;
     5         HashMap<String, List<String>> map = new HashMap<String, List<String>>();
     6         for (int i=0; i<strings.length; i++) {
     7             String temp = shift(strings[i]);
     8             if (map.containsKey(temp)) {
     9                 map.get(temp).add(strings[i]);
    10             }
    11             
    12             else {
    13                 List<String> li= new ArrayList<String>();
    14                 li.add(strings[i]);
    15                 map.put(temp, li);
    16             }
    17             
    18         }
    19         for (List<String> each : map.values()) {
    20             Collections.sort(each);
    21             res.add(new ArrayList<String>(each));
    22         }
    23         return res;
    24     }
    25     
    26     public String shift(String cur) {
    27         StringBuffer res = new StringBuffer();
    28         int len = cur.length();
    29         int dist = cur.charAt(0) - 'a';
    30         for (int k=0; k<len; k++) {
    31             //res.append((cur.charAt(k)+j>'z')? ('a'+(int)(cur.charAt(k)+j-'z')-1) : (cur.charAt(k)+j));
    32             char c = cur.charAt(k);
    33             res.append((c-'a'-dist+26)%26+'a');
    34         }
    35         return res.toString();
    36     }
    37 }
  • 相关阅读:
    C#利用反射动态调用类及方法
    系统程序监控软件
    SQL server 2008 安装和远程访问的问题
    sql server 创建临时表
    IIS 时间问题
    windows 2008 安装 sql server 2008
    sql server xml nodes 的使用
    Window 7sp1 安装vs2010 sp1 打开xaml文件崩溃
    CSS资源网址
    Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5065432.html
Copyright © 2020-2023  润新知