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"],
    A solution is:

    [
      ["abc","bcd","xyz"],
      ["az","ba"],
      ["acef"],
      ["a","z"]
    ]
     
    Solution:
    public class Solution {
        public List<List<String>> groupStrings(String[] strings) {
            List<List<String>> resLists = new LinkedList<List<String>>();
            
            HashMap<String,List<String>> patternMap = new HashMap<String,List<String>>();
            for (String str : strings){
                StringBuilder builder = new StringBuilder().append(str);
                int delta = builder.charAt(0)-'a';
                builder.setCharAt(0,'a');
                for (int i=1;i<builder.length();i++){
                    char c = (char) ((builder.charAt(i) + 26 - delta)%26);
                    builder.setCharAt(i,c);
                }
                String pattern = builder.toString();
                if (!patternMap.containsKey(pattern)){
                    patternMap.put(pattern,new LinkedList<String>());
                }
                patternMap.get(pattern).add(str);
            }
            
            for (List<String> strList : patternMap.values()){
                resLists.add(strList);
            }
            return resLists;
        }
    }
  • 相关阅读:
    一款开源免费跨浏览器的视频播放器--videojs使用介绍(转)
    forward内部跳转 和redirect重定向跳转的区别
    心理学--斯纳金
    心理学--大脑
    心理学--普及
    经济--国债,外汇
    经济--公积金
    经济--技术分析
    经济--分级基金3
    经济--分级基金
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5870504.html
Copyright © 2011-2022 走看看