[LeetCode] Odd String Difference

2451. Odd String Difference

You are given an array of equal-length strings words. Assume that the length of each string is n.

Each string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of ‘a’ is 0, ‘b’ is 1, and ‘z’ is 25.

  • For example, for the string “acb”, the difference integer array is [2 - 0, 1 - 2] = [2, -1].

All the strings in words have the same difference integer array, except one. You should find that string.

Return the string in words that has different difference integer array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Solution {
vector<int> diff(string s) {
vector<int> res;
for(int i = 0; i < s.length() - 1; i++) {
res.push_back(s[i + 1] - s[i]);
}
return res;
}
public:
string oddString(vector<string>& words) {
vector<int> d1 = diff(words[0]), d2 = diff(words[1]);
if(d1 != d2) {
vector<int> d3 = diff(words[2]);
if(d1 == d3) return words[1];
return words[0];
}
for(int i = 2; i < words.size(); i++) {
vector<int> d = diff(words[i]);
if(d1 != d) return words[i];
}
return "";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/30/PS/LeetCode/odd-string-difference/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.