Skip to content

Commit

Permalink
Add some code
Browse files Browse the repository at this point in the history
  • Loading branch information
codeAbinash committed Jun 7, 2024
1 parent 0d11eb3 commit c7fb9e3
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
70 changes: 70 additions & 0 deletions leetcode/problems/cpp/replace-words.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#include "sstream"
#include "string"
#include "vector"

using namespace std;

class Trie {
public:
bool isEnd;
Trie* children[26];

Trie() {
isEnd = false;
for (int i = 0; i < 26; i++) {
children[i] = nullptr;
}
isEnd = false;
}
};

class Solution {
public:
Trie* root;
Solution() { root = new Trie(); }

void insert(string word) {
Trie* node = root;
for (char c : word) {
int i = c - 'a';
if (node->children[i] == nullptr) {
node->children[i] = new Trie();
}
node = node->children[i];
}
node->isEnd = true;
}

string search(string word) {
Trie* node = root;
string result;
for (char c : word) {
int i = c - 'a';
if (node->children[i] == nullptr) {
return word;
}
result += c;
if (node->children[i]->isEnd) {
return result;
}
node = node->children[i];
}
return word;
}

string replaceWords(vector<string>& dictionary, string sentence) {
for (string word : dictionary) {
insert(word);
}

stringstream ss(sentence);
string word, result;
while (ss >> word) {
if (!result.empty()) {
result += " ";
}
result += search(word);
}
return result;
}
};
24 changes: 24 additions & 0 deletions leetcode/problems/java/longest-palindrome.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import java.util.HashMap;
import java.util.Map;

class Solution {
public int longestPalindrome(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}

int result = 0;
boolean hasOdd = false;
for (int count : map.values()) {
if (count % 2 == 0) {
result += count;
} else {
result += count - 1;
hasOdd = true;
}
}

return hasOdd ? result + 1 : result;
}
}

0 comments on commit c7fb9e3

Please sign in to comment.