Leetcode 2451. Odd String Difference
You are given an array of strings words
. Each string consists of lowercase English letters and has the same length.
We’ll define the difference value of a string as an array of integers, where each integer represents the difference between the ASCII values of consecutive characters in the string.
For example, the difference value of “abcd” is [b-a, c-b, d-c]
which translates to [1, 1, 1]
.
Your task is to find and return the unique string within the array words
based on these difference values. It is guaranteed that there is exactly one such unique string.
words
words
are of the same length.#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
vector<int> getDifferenceValue(const string &s) {
vector<int> diff;
for (int i = 1; i < s.length(); ++i) {
diff.push_back(s[i] - s[i - 1]);
}
return diff;
}
string oddStringDifference(vector<string>& words) {
unordered_map<string, vector<string>> diffMap;
for (const auto& word : words) {
vector<int> diffVec = getDifferenceValue(word);
string diffStr;
for (const int& num : diffVec) {
diffStr += to_string(num) + ",";
}
diffMap[diffStr].push_back(word);
}
for (const auto& entry : diffMap) {
if (entry.second.size() == 1) {
return entry.second[0];
}
}
return ""; // This line should not be reached due to problem constraints
}
int main() {
vector<string> words = {"adc", "wzy", "abc"};
cout << oddStringDifference(words) << endl;
return 0;
}
Thus, the overall time complexity is (O(n \times m)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?