vault backup: 2022-09-05 19:27:02

This commit is contained in:
juan 2022-09-05 19:27:02 +08:00
parent 1e7601d337
commit 278e5100e9
3 changed files with 144 additions and 1 deletions

View file

@ -39,6 +39,6 @@
"repelStrength": 10, "repelStrength": 10,
"linkStrength": 1, "linkStrength": 1,
"linkDistance": 250, "linkDistance": 250,
"scale": 0.7463733455586773, "scale": 1.3711753906745523,
"close": true "close": true
} }

View file

@ -0,0 +1,35 @@
# Greedy Algorithm
2022-09-05 17:32
> ##### Algorithms:
>
> #algorithm #greedy
>
> ##### Difficulty:
>
> #CS_analysis
>
> ##### Additional tags:
##### Related problems:
```expander
tag:#coding_problem tag:#<CHANGE_ME> -tag:#template_remove_me
```
##### Links:
- [cppreference]()
---
### What is Greedy Algorithm?
### How does Greedy Algorithm work?
#### Example code
### Why and when to use it?
#template_remove_me

View file

@ -0,0 +1,108 @@
# Leetcode Longest-Palindrome
2022-09-05 17:27
> ##### Algorithms:
>
> #algorithm #greedy
>
> ##### Data structures:
>
> #DS #string
>
> ##### Difficulty:
>
> #coding_problem #difficulty-easy
>
> ##### Additional tags:
>
> #leetcode
>
> ##### Revisions:
>
> N/A
##### Links:
- [Link to problem](https://leetcode.com/problems/longest-palindrome/)
---
### Problem
Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters.
Letters are **case sensitive**, for example, `"Aa"` is not considered a palindrome here.
#### Examples
**Example 1:**
**Input:** s = "abccccdd"
**Output:** 7
**Explanation:** One longest palindrome that can be built is "dccaccd", whose length is 7.
**Example 2:**
**Input:** s = "a"
**Output:** 1
**Explanation:** The longest palindrome that can be built is "a", whose length is 1.
#### Constraints
- `1 <= s.length <= 2000`
- `s` consists of lowercase **and/or** uppercase English letters only.
### Thoughts
> [!summary]
> This is a #greedy problem.
The solution is simple: count the apperances, sort it using
std::greater<int>(), and select all even number, for odd
number `i`:
- if odd numbers has been used: `ans += i - 1` (make it
even)
- if not: `ans += i`, and mark odd number used
### Solution
```cpp
class Solution {
public:
int longestPalindrome(string s) {
int ans = 0;
bool used = false;
vector<int> table(52, 0);
// record in table.
for (char ch : s) {
if (ch <= 'Z') {
table[ch - 'A' + 26]++;
} else {
table[ch - 'a']++;
}
}
sort(table.begin(), table.end(), greater<int>());
for (int i : table) {
if (i % 2 == 1) {
if (used == false) {
used = true;
ans += i;
} else {
ans += i - 1;
}
} else {
if (i == 0) {
break;
}
ans += i;
}
}
return ans;
}
};
```