Leetcode 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"]
]

 1 public class Solution {
 2     public IList<IList<string>> GroupStrings(string[] strings) {
 3         var result = new List<IList<string>>();    
 4         
 5         foreach (var s in strings)
 6         {
 7             bool found = false;
 8             
 9             foreach (var l in result)
10             {
11                 if (l.Count > 0 && CanShift(l[0], s))
12                 {
13                     l.Add(s);
14                     found = true;
15                     break;
16                 }
17             }
18             
19             if (!found)
20             {
21                 result.Add(new List<string>() {s});
22             }
23         }
24         
25         return result;
26     }
27     
28     private bool CanShift(string w1, string w2)
29     {
30         if (w1.Length != w2.Length) return false;
31         if (w1.Length < 2) return true;
32         
33         int dist = 0;
34         for (int i = 0; i < w1.Length; i++)
35         {
36             int d1 = (int)w1[i] - (int)'a';
37             int d2 = (int)w2[i] - (int)'a';
38             
39             int delta = d2 < d1 ? d2 + 26 - d1 : d2 - d1;
40             
41             if (i == 0)
42             {
43                 dist = delta;
44             }
45             else
46             {
47                 if (dist != delta) return false;
48             }
49         }
50         
51         return true;
52     }
53 }
54         
55         

 

posted @ 2017-12-19 01:43  逸朵  阅读(218)  评论(0)    收藏  举报