• 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

  • 相关阅读:
    php解决前端调接口跨域问题
    降低token 被盗风险安全问题
    u盘怎么解除写保护状态,u盘写保护怎么去掉
    安装vsftpd时出现错误
    对于vim 编译器的设置
    Vim 怎么设置显示行号,永久性显示行号
    Ubuntu系统设置过程中信息显示不全
    控制文件夹名显示的长短
    linux中好玩的游戏
    安装VMware Tools
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4868855.html
Copyright © 2020-2023  润新知