-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0d11eb3
commit c7fb9e3
Showing
2 changed files
with
94 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |