-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_string_problem.cpp
More file actions
135 lines (121 loc) · 2.92 KB
/
leetcode_string_problem.cpp
File metadata and controls
135 lines (121 loc) · 2.92 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
https : // leetcode.com/problems/remove-all-adjacent-duplicates-in-string/description/
class Solution
{
public:
string removeDuplicates(string s)
{
string ans = "";
int index = 0;
while (index < s.length())
{
// same
// ans ka rightmost character and string s ka current character
if (ans.length() > 0 && ans[ans.length() - 1] == s[index])
{
// pop from ans string
ans.pop_back();
}
else
{
// push
ans.push_back(s[index]);
}
index++;
}
return ans;
}
};
https : // leetcode.com/problems/remove-all-occurrences-of-a-substring/
class Solution
{
public:
string removeOccurrences(string s, string part)
{
while (s.find(part) != string::npos)
{
// if inside loop, it means that part exists in s string
s.erase(s.find(part), part.length());
}
return s;
}
};
https : // leetcode.com/problems/valid-palindrome-ii/
class Solution
{
public:
bool checkPalindrome(string s, int i, int j)
{
while (i <= j)
{
if (s[i] != s[j])
{
return false;
}
else
{
i++;
j--;
}
}
return true;
}
bool validPalindrome(string s)
{
int i = 0;
int j = s.length() - 1;
while (i <= j)
{
if (s[i] == s[j])
{
i++;
j--;
}
else
{
// s[i]!=s[j]
// 1 removal allowed
// check plaindrome for remaining string after removal
// ith character -> remove
bool ans1 = checkPalindrome(s, i + 1, j);
// jth character -> remove
bool ans2 = checkPalindrome(s, i, j - 1);
return ans1 || ans2;
}
}
// agar yha tk pohoche ho
// iska matlab valid palindrome hai
// iska matlab -> 0 removal
return true;
}
};
https : // leetcode.com/problems/palindromic-substrings/
class Solution
{
public:
int expand(string s, int i, int j)
{
int count = 0;
while (i >= 0 && j < s.length() && s[i] == s[j])
{
count++;
i--;
j++;
}
return count;
}
int countSubstrings(string s)
{
int totalCount = 0;
for (int i = 0; i < s.length(); i++)
{
// ODD
int j = i;
int oddKaAns = expand(s, i, j);
// EVEN
j = i + 1;
int evenKaAns = expand(s, i, j);
totalCount = totalCount + oddKaAns + evenKaAns;
}
return totalCount;
}
};