zoukankan      html  css  js  c++  java
  • 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 很重要。因此单独写了函数shiftStr, 

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


    Java code:

    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            if (strings == null) {
                throw new IllegalArgumentException("strings is null");
            }
            List<List<String>> result = new ArrayList<List<String>>();
            if(strings.length == 0){
                return result;
            }
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            for(String str: strings) {
                String shifted_str = shiftStr(str);
                if(map.containsKey(shifted_str)){
                    map.get(shifted_str).add(str);
                }else{
                    List<String> item = new ArrayList<String>();
                    item.add(str);
                    map.put(shifted_str, item);
                    result.add(item);
                }
            }
            for(List<String> list: result) {
                Collections.sort(list);
            }
            return result;
        }
        
        private String shiftStr(String str){
            StringBuilder buffer = new StringBuilder();
            char[] char_array = str.toCharArray();
            int dist = str.charAt(0) - 'a';
            for(char c: char_array){
                buffer.append((c - 'a' - dist + 26) % 26 + 'a');
            }
            return buffer.toString();
        }
    }

    Reference:

    1. https://leetcode.com/discuss/58003/java-solution-with-separate-shiftstr-function

  • 相关阅读:
    分段路由的复兴
    动态维护FDB表项实现VXLAN通信
    neutron dhcp 高可用
    wpf
    从0到1设计一台8bit计算机
    哇塞的Docker——vscode远程连接Docker容器进行项目开发(三)
    中通消息平台 Kafka 顺序消费线程模型的实践与优化
    飞机大战 python小项目
    看透确定性,抛弃确定性
    如何根据普通ip地址获取当前地理位置
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4868855.html
Copyright © 2011-2022 走看看