码迷,mamicode.com
首页 > 其他好文 > 详细

249. Group Shifted Strings

时间:2018-06-29 01:17:37      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:diff   另一个   long   success   public   enc   seq   ++   forms   

问题描述:

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;
    }
};

 

249. Group Shifted Strings

标签:diff   另一个   long   success   public   enc   seq   ++   forms   

原文地址:https://www.cnblogs.com/yaoyudadudu/p/9241471.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!