1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

problems(cpp): add „1657. Determine if Two Strings Are Close“

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-12-02 20:13:07 +01:00
parent fb8f4944c8
commit 5d51c78a08
Signed by: mfocko
GPG key ID: 7C47D46246790496
5 changed files with 82 additions and 0 deletions

View file

@ -0,0 +1 @@
../../problems/two-sum.swift

View file

@ -0,0 +1 @@
../../problems/valid-parentheses.swift

View file

@ -0,0 +1,43 @@
#include <algorithm>
#include <array>
#include <string>
class Solution {
using freq_t = std::array<std::size_t, 26>;
freq_t freqs(const std::string& word)
{
freq_t f { 0 };
for (auto c : word) {
f[c - 'a']++;
}
return f;
}
int mask(const freq_t& f)
{
int m = 0;
for (auto c : f) {
m = (m << 1) | (c > 0);
}
return m;
}
public:
bool closeStrings(std::string word1, std::string word2)
{
auto f1 = freqs(word1);
auto m1 = mask(f1);
std::sort(f1.begin(), f1.end());
auto f2 = freqs(word2);
auto m2 = mask(f2);
std::sort(f2.begin(), f2.end());
return m1 == m2 && f1 == f2;
}
};

15
problems/two-sum.swift Normal file
View file

@ -0,0 +1,15 @@
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var encountered: [Int: Int] = [:]
for (i, x) in nums.enumerated() {
if encountered[target - x] != nil {
return [encountered[target - x]!, i]
}
encountered[x] = i
}
return []
}
}

View file

@ -0,0 +1,22 @@
class Solution {
func isValid(_ s: String) -> Bool {
var stack: [Character] = []
for c in s {
switch c {
case "(":
stack.append(")")
case "{":
stack.append("}")
case "[":
stack.append("]")
default:
if (stack.popLast() != c) {
return false
}
}
}
return stack.isEmpty
}
}