Skip to content

3043 find the length of the longest common prefix#62

Open
kitano-kazuki wants to merge 2 commits into
mainfrom
3043-find-the-length-of-the-longest-common-prefix
Open

3043 find the length of the longest common prefix#62
kitano-kazuki wants to merge 2 commits into
mainfrom
3043-find-the-length-of-the-longest-common-prefix

Conversation

@kitano-kazuki
Copy link
Copy Markdown
Owner

Comment thread memo.md
@@ -1 +1,248 @@
# Step1

## アプローチ
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

自分も解いてみました。 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);
    }
};

Comment thread memo.md

## Code2-2 (Hash)

* Hashを使う方法もあるらしい
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hash を使うと書いてしまうと、ハッシュ関数を用いて prefix のハッシュ値を求めて何かを行うのかと誤解させてしまうかもしれません。集合を使うと書いたほうが、読み手にとって正確に理解できると思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants