some more neetcode

This commit is contained in:
Kaushik Narayan R 2023-10-20 20:58:44 -07:00
parent 42c44952c5
commit df57a62275
8 changed files with 97 additions and 2 deletions

11
1-two-sum/driver.cpp Normal file
View File

@ -0,0 +1,11 @@
#include "soln.hpp"
int main()
{
vector<int> nums{2, 7, 11, 15};
int target = 9;
vector<int> answer{0, 1};
Solution soln;
cout << "Found two-sum indices correctly? " << soln.test(nums, target, answer) << endl;
return 0;
}

24
1-two-sum/soln.cpp Normal file
View File

@ -0,0 +1,24 @@
#include "soln.hpp"
vector<int> Solution::twoSum(vector<int> &nums, int target)
{
vector<int> result(2);
for (int i = 0; i < nums.size(); i++)
{
for (int j = i + 1; j < nums.size(); j++)
{
if (nums[i] + nums[j] == target)
{
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
bool Solution::test(vector<int> &nums, int target, vector<int> &answer)
{
return twoSum(nums, target) == answer;
}

8
1-two-sum/soln.hpp Normal file
View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target);
bool test(vector<int> &nums, int target, vector<int> &answer);
};

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
string s = "A man, a plan, a canal: Panama";
bool answer = true;
Solution soln;
cout << "Checked palindrome correctly? " << soln.test(s, answer) << endl;
return 0;
}

View File

@ -0,0 +1,32 @@
#include "soln.hpp"
bool Solution::isPalindrome(string s)
{
int n = s.length();
if (n < 2)
return true;
for (int i = 0; i < n; i++)
{
if (s[i] >= 'A' && s[i] <= 'Z')
s[i] += 32;
if ((s[i] < 'a' || s[i] > 'z') &&
(s[i] < '0' || s[i] > '9'))
{
s.erase(s.begin() + i);
i--;
n--;
}
}
n = s.length();
for (int i = 0, j = n - 1; i < n / 2; i++, j--)
{
if (s[i] != s[n - i - 1])
return false;
}
return true;
}
bool Solution::test(string s, bool answer)
{
return isPalindrome(s) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool isPalindrome(string s);
bool test(string s, bool answer);
};

View File

@ -1,6 +1,7 @@
#include "soln.hpp" #include "soln.hpp"
int main() { int main()
{
string s = "({[[[]]]})"; string s = "({[[[]]]})";
bool answer = true; bool answer = true;
Solution soln; Solution soln;

View File

@ -37,6 +37,7 @@ bool Solution::isValid(string s)
return bstack.size() == 0; return bstack.size() == 0;
} }
bool Solution::test(string s, bool answer) { bool Solution::test(string s, bool answer)
{
return isValid(s) == answer; return isValid(s) == answer;
} }