forked from subailong/datalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrings.cpp
102 lines (77 loc) · 1.64 KB
/
strings.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//
// strings.cpp
// datalgo
//
// Created by Iyed Bennour on 11/11/2014.
// Copyright (c) 2014 Iyed Bennour. All rights reserved.
//
#include "strings.h"
#include <iostream>
#include <unordered_map>
#include <map>
bool str_in_str(const char *str1, const char *str2) {
const char *p1 = str1;
const char *p2 = str2;
while (*p2 != '\0') {
if (*p2 == *p1) {
p2++;
p1++;
while (*p1 == *p2 && *p2 != '\0' && *p1 != '\0') {
p1++;
p2++;
}
if (*p1 == '\0') return true;
}
else {
p2++;
}
p1 = str1;
}
return false;
}
void reverse_string(std::string& s) {
for (int i = 0; i < s.length() / 2; i++) {
std::swap(s[i], s[s.length() - 1 - i]);
}
}
char find_first_non_repeating_char(const std::string& s) {
char c = '\0';
std::unordered_map<char, size_t> hashmap;
for (auto i: s) {
auto it2 = hashmap.find(i);
if (it2 != hashmap.end()) {
hashmap[i] += 1;
}
else
hashmap[i] = 1;
}
for (auto i:s) {
if (hashmap[i] == 1) {
c = i;
break;
}
}
return c;
}
bool is_palindrome(const char *s, size_t len) {
for (int i = 0; i < len/2; i++) {
if (s[i] != s[len - 1 - i])
return false;
}
return true;
}
bool test_string_in_string() {
const char *s1 = "iyed";
const char *s2 = "bennour iyed";
return str_in_str(s1, s2);
}
bool test_reverse_string() {
std::string s("bennour");
reverse_string(s);
return s == std::string("ruonneb");
}
bool test_find_first_non_repeating_char() {
std::string s("dcbaa");
char c = find_first_non_repeating_char(s);
return c == 'd';
}