[LeetCode] Count Almost Equal Pairs I

3265. Count Almost Equal Pairs I

You are given an array nums consisting of positive integers.

We call two integers x and y in this problem almost equal if both integers can become equal after performing the following operation at most once:

  • Choose either x or y and swap any two digits within the chosen number.

Return the number of indices i and j in nums where i < j such that nums[i] and nums[j] are almost equal.

Note that it is allowed for an integer to have leading zeros after performing an operation.

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

class Solution {
bool ok(int x, int y) {
string s1 = to_string(x), s2 = to_string(y);
if(s1.length() > s2.length()) swap(s1,s2);
for(int i = 0; i < s2.length(); i++) {
for(int j = i; j < s2.length(); j++) {
swap(s2[i], s2[j]);
if(stoi(s1) == stoi(s2)) return true;
swap(s2[i], s2[j]);
}
}
return false;
}
public:
int countPairs(vector<int>& nums) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
for(int j = i + 1; j < nums.size(); j++) {
if(ok(nums[i], nums[j])) res++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/25/PS/LeetCode/count-almost-equal-pairs-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.