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.

Example:

Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output: 
[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]

解题思路:

使用visited函数来判断该字符串是否已经被访问并且加入到某一个组内。

若加入则跳过

若未加入,则判断或寻找它的组员

需要注意的是:

在判断是否可以通过偏移来获得另一个字符串时,注意当被减数大于减数时如何判断:

 s1[i] - 'a' + ('z' - s2[i]) +1;

代码:

class Solution {
public:
    vector<vector<string>> groupStrings(vector<string>& strings) {
        vector<bool> visited(strings.size(), false);
        vector<vector<string>> ret;
        for(int i = 0; i < strings.size(); i++){
            if(visited[i]) continue;
            visited[i] = true;
            vector<string> cur;
            cur.push_back(strings[i]);
            for(int j = i+1; j < strings.size(); j++){
                if(visited[j]) continue;
                if(canShift(strings[i], strings[j])){
                    cur.push_back(strings[j]);
                    visited[j] = true;
                }
            }
            ret.push_back(cur);
        }        
        return ret;
    }
private: 
    bool canShift(string s1, string s2){
        if(s1.size() != s2.size()){
            return false;
        }
        if(s1.size() == 1)
            return true;
        int diff = s1[0] >= s2[0] ? s1[0] - s2[0] : s1[0] - 'a' + ('z' - s2[0]) + 1;
        for(int i = 1; i < s1.size(); i++){
            int curdiff = s1[i] >= s2[i] ? s1[i] - s2[i] : s1[i] - 'a' + ('z' - s2[i]) +1;
            if(curdiff != diff)
                return false;
        }
        return true;
    }
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9241471.html
今日推荐