---
# System prepended metadata

title: 2246. Longest Path With Different Adjacent Characters
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

# 2246. Longest Path With Different Adjacent Characters

###### Link : https://leetcode.com/problems/longest-path-with-different-adjacent-characters/

## 題目
計算相鄰節點不連續字母最長路徑
## 程式碼

```cpp=
class Solution {
public:
    int longestPath(vector<int>& parent, string s) {
        vector<vector<int>> child(parent.size(), vector<int>());
        for(int i=1; i<parent.size();i++){//節點擁有的小孩
            child[parent[i]].push_back(i);
        }
        this->parent.assign(parent.begin(), parent.end());//複製到private中的parent
        Solve(0, child, s);
        return _max;
    }
private:
    vector<int> parent;
    int _max;//最長路徑
    int Solve(int node, vector<vector<int>> &child, string &s){
        int longest=0, longest2=0;
        for(auto &it : child[node]){//走過這個note的所有小孩
            int temp = Solve(it, child, s);
            if(longest<temp){
                longest2 = longest;
                longest = temp;
            }
            else if(longest2<temp)
                longest2 = temp;
        }
        if(_max < longest + longest2 + 1)//經過自己在往子節點走的路徑
            _max = longest + longest2 + 1;//+1為加上自己
        if(node!=0 && s[node] == s[parent[node]])
            return 0;
        return (longest > longest2)? longest+1 : longest2+1;//回傳加上自己的最長路徑
    }
};
```