249. 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:

思路: 將strs按照規(guī)律編碼Map(code_str -> list(string)) 歸到不同類,輸出各list(string)。
區(qū)別他們不同的是str的length 和 他們在字符表中之間的相對位置,shift后也不變。
相對位置可以 以 第一個(gè)字符在字符表中的位置 做參照標(biāo)準(zhǔn)(encode1) 或以 前一個(gè)字符在字符表中的位置 為參照坐標(biāo)(encode2)

Time Complexity: O(mn) Space Complexity: O(mn) 不算結(jié)果
m個(gè)str,長度為n

Solution Code:

class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> result = new ArrayList<List<String>>();
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        
        //encode
        for (String str : strings) {
            String key = encode1(str);
            if (!map.containsKey(key)) {
                List<String> list = new ArrayList<String>();
                map.put(key, list);
            }
            map.get(key).add(str);
        }
        
        // prepare the result
        for (String key : map.keySet()) {
            List<String> list = map.get(key);
            // Collections.sort(list);
            result.add(list);
        }
        return result;
    }
    
    private String encode1(String str) {
        String key = "";
        for (int i = 0; i < str.length(); i++) {
            char c = (char) (str.charAt(i) - str.charAt(0) + 'a');
            if (c < 'a') c += 26;
            key += c;
        }
        return key;
    }
    private String encode2(String str) {
        String key = "";
        for (int i = 0; i < str.length(); i++) {
            char c = (char) (str.charAt(i) - str.charAt(0) + 'a');
            if (c < 'a') c += 26;
            key += c;
        }
        return key;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容