-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.cpp
78 lines (62 loc) · 1.85 KB
/
common.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "common.h"
#include <unistd.h>
#include <string.h>
#include <algorithm>
const char *get_ext(const char *filename, size_t length) {
if (length == 0) {
length = strlen(filename);
}
for (const char *p = filename + length - 1; length > 0; --p, --length) {
if (*p == '.') {
return p;
}
}
return NULL;
}
const char *get_ext(const string &filename) {
return get_ext(filename.c_str(), filename.length());
}
bool is_exist(const char *filename) { return access(filename, F_OK) == 0; }
bool is_exist(const string &filename) { return is_exist(filename.c_str()); }
void get_date(char *date) {
time_t t = time(NULL);
tm *ltm = localtime(&t);
sprintf(date, "%4d/%02d/%02d", ltm->tm_year + 1900, ltm->tm_mon + 1,
ltm->tm_mday);
}
bool all_nums(const char *s) {
if (*s == '\0') {
return false;
}
while (*s && isdigit(*s)) {
++s;
}
return *s == '\0';
}
#define min(a, b) ((a < b) ? a : b)
size_t edit_distance(const char *s1, size_t len1, const char *s2, size_t len2) {
#define DP(i, j) dp[(i) * (len2 + 1) + (j)]
// dp should be longer than dp[(len1+1)*(len2+1)]
size_t *dp = new size_t[(len1 + 1) * (len2 + 1)];
for (size_t i = 0; i <= len1; ++i) {
DP(i, 0) = i;
}
for (size_t i = 0; i <= len2; ++i) {
DP(0, i) = i;
}
size_t flag;
for (size_t i = 1; i <= len1; ++i) {
for (size_t j = 1; j <= len2; ++j) {
flag = (s1[i - 1] == s2[j - 1]) ? 0 : 1;
DP(i, j) = min(DP(i - 1, j) + 1,
min(DP(i, j - 1) + 1, DP(i - 1, j - 1) + flag));
}
}
size_t ret = DP(len1, len2);
delete[] dp;
return ret;
#undef DP
}
size_t edit_distance(const string &s1, const string &s2) {
return edit_distance(s1.c_str(), s1.length(), s2.c_str(), s2.length());
}