Skip to content

Instantly share code, notes, and snippets.

class Solution {
public:
bool validPalindrome(string s) {
return valid(s, 0, s.length() - 1, 1);
}
bool valid(string& s, int i, int j, int d) {
if (i >= j) return true;
if (s[i] == s[j])
return valid(s, i + 1, j - 1, d);
else
class Solution {
public:
bool checkPerfectNumber(int num) {
int result = 1;
for(int i = 2; i < sqrt(num); i++) {
if (num%i == 0) {
//cout << result << ", " << i << endl;
result += i + num/i;
}
}
class Solution {
public:
bool wordPattern(string pattern, string str) {
str += ' ';
int i = 0, j = 0, len1 = pattern.size(), len2 = str.size();
unordered_map<char, string> hash1;
unordered_map<string, char> hash2;
while(i < len1 && j < len2) {
int pos = str.find(' ', j);
string s = str.substr(j, pos-j);
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> res(26);
for(int i = 0; i < magazine.size(); i++)
++res[magazine[i]];
for(int j = 0; j < ransomNote.size(); j++)
if (--res[ransomNote[j]] < 0) return false;
return true;
}
class Solution {
public:
int calculate(string s) {
s += "+";
stack<int> st;
char old = '+';
for(int i = 0, left = 0; i < s.size(); i++) {
if (isdigit(s[i]) || isspace(s[i])) continue;
int val = stoi(s.substr(left, i-left));
if (old == '+' || old == '-') st.push(old == '+' ? val : -val);
class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
for(int i = 1; i < matrix.size(); i++) {
for(int j = 1; j < matrix[i].size(); j++) {
if (matrix[i][j] != matrix[i-1][j-1]) return false;
}
}
return true;
}
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for(int i = 0; i < n; i++) {
for(int j = 0; j < i; j++)
swap(matrix[i][j], matrix[j][i]);
}
for(int i = 0; i < n; i++)
class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> res;
for(int i = left; i <= right; i++) {
int t = i;
bool val = true;
while(t && val) {
const int r = t % 10;
//cout << "r: " << r << ", i:" << i << ", i%r" << i%r << endl;
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int maxi = -1, seci = -1;
for(int i = 0; i < nums.size(); i++) {
// cout << "b: i: " << i << " m: " << maxi << ", s: " << seci << endl;
if (nums[i] > nums[maxi]) {
int tmp = maxi;
maxi = i;
seci = tmp;