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:
parent
fb8f4944c8
commit
5d51c78a08
5 changed files with 82 additions and 0 deletions
1
grind75/week-1/two-sum.swift
Symbolic link
1
grind75/week-1/two-sum.swift
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../problems/two-sum.swift
|
1
grind75/week-1/valid-parentheses.swift
Symbolic link
1
grind75/week-1/valid-parentheses.swift
Symbolic link
|
@ -0,0 +1 @@
|
|||
../../problems/valid-parentheses.swift
|
43
problems/determine-if-two-strings-are-close.cpp
Normal file
43
problems/determine-if-two-strings-are-close.cpp
Normal 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
15
problems/two-sum.swift
Normal 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 []
|
||||
}
|
||||
}
|
22
problems/valid-parentheses.swift
Normal file
22
problems/valid-parentheses.swift
Normal 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
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue