add trick example of greatest-common-divisor, knuth-morris-pratt, primality-test, quick-pow, split-text
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
int greatest_common_divisor(int num1, int num2) {
|
||||
while (num2 != 0) {
|
||||
int temp = num2;
|
||||
num2 = num1 % num2;
|
||||
num1 = temp;
|
||||
}
|
||||
return num1;
|
||||
}
|
@@ -0,0 +1,29 @@
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
int knuth_morris_pratt(const std::string text, const std::string pattern) {
|
||||
int n = text.length(), m = pattern.length();
|
||||
std::vector<int> next(m, 0);
|
||||
for (int i = 1, j = 0; i < m; i++) {
|
||||
while (j > 0 && pattern[i] != pattern[j]) {
|
||||
j = next[j - 1];
|
||||
}
|
||||
if (pattern[i] == pattern[j]) {
|
||||
j++;
|
||||
}
|
||||
next[i] = j;
|
||||
}
|
||||
|
||||
for (int i = 0, j = 0; i < n; i++) {
|
||||
while (j > 0 && text[i] != pattern[j]) {
|
||||
j = next[j - 1];
|
||||
}
|
||||
if (text[i] == pattern[j]) {
|
||||
j++;
|
||||
}
|
||||
if (j == m) {
|
||||
return i - m + 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
@@ -0,0 +1,17 @@
|
||||
#include <vector>
|
||||
|
||||
bool primality_check(int n) {
|
||||
std::vector<bool> is_prime(n + 1, true);
|
||||
if (n <= 2) {
|
||||
return false;
|
||||
}
|
||||
is_prime[0] = is_prime[1] = false;
|
||||
for (int i = 2; i * i <= n; i++) {
|
||||
if (is_prime[i]) {
|
||||
for (int j = i * i; j <= n; j += i) {
|
||||
is_prime[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return is_prime[n];
|
||||
}
|
@@ -0,0 +1,11 @@
|
||||
long long quick_pow(int base, int power) {
|
||||
long long ans = 1;
|
||||
while (power > 0) {
|
||||
if (power & 1) {
|
||||
ans *= base;
|
||||
}
|
||||
base *= base;
|
||||
power >>= 1;
|
||||
}
|
||||
return ans;
|
||||
}
|
13
trick/split-text.cpp
Normal file
13
trick/split-text.cpp
Normal file
@@ -0,0 +1,13 @@
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
std::vector<std::string> split(std::string target, std::string pattern) {
|
||||
std::vector<std::string> res;
|
||||
size_t start = 0, next = 0;
|
||||
while ((next = target.find(pattern, start)) != std::string::npos) {
|
||||
res.push_back(target.substr(start, next - start));
|
||||
start = next + pattern.length();
|
||||
}
|
||||
res.push_back(target.substr(start));
|
||||
return res;
|
||||
}
|
Reference in New Issue
Block a user