3043 find the length of the longest common prefix#62
Open
kitano-kazuki wants to merge 2 commits into
Open
Conversation
nodchip
reviewed
May 27, 2026
| @@ -1 +1,248 @@ | |||
| # Step1 | |||
|
|
|||
| ## アプローチ | |||
There was a problem hiding this comment.
自分も解いてみました。 Trie 木を 2 つ作り、同時に dfs し、最大の高さを求めました。業務のコードでは、メモリを解放しないとまずいです。
class Solution {
public:
struct Node {
Node* children[10] = {};
};
Node* ToTrie(const vector<int>& arr) {
Node* root = new Node();
for (int integer : arr) {
std::string s = std::to_string(integer);
Node* node = root;
for (char ch : s) {
int digit = ch - '0';
if (!node->children[digit]) {
node->children[digit] = new Node();
}
node = node->children[digit];
}
}
return root;
}
int GetHeight(Node* node1, Node* node2) {
if (!node1 || !node2) {
return -1;
}
int max_height = 0;
for (int digit = 0; digit < 10; ++digit) {
int height = GetHeight(node1->children[digit], node2->children[digit]) + 1;
max_height = max(max_height, height);
}
return max_height;
}
int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) {
Node* root1 = ToTrie(arr1);
Node* root2 = ToTrie(arr2);
return GetHeight(root1, root2);
}
};|
|
||
| ## Code2-2 (Hash) | ||
|
|
||
| * Hashを使う方法もあるらしい |
There was a problem hiding this comment.
Hash を使うと書いてしまうと、ハッシュ関数を用いて prefix のハッシュ値を求めて何かを行うのかと誤解させてしまうかもしれません。集合を使うと書いたほうが、読み手にとって正確に理解できると思います。
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
https://leetcode.com/problems/find-the-length-of-the-longest-common-prefix/description