Graph题目总结不定期更新
Posted goldenticket
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Graph题目总结不定期更新相关的知识,希望对你有一定的参考价值。
Find minimal ops to convert one str to another
Description Given two alphabet strings str1 and str2. You can change the characters in str1 to any alphabet characters in order to transform str1 to str2. One restriction is, in each operation, you should change all the same characters simultaneously. What‘s more, you may use another special character * if necessary, which means during each operations, you may change the alphabet characters to *, or change each * to a specific character. We want to know the minimum operation times. If impossible, return -1. Templateint MinOpTimes(string str1, string str2) { //...
};
str1: accs, str2: eeec
operation 1: change ‘a‘->‘e‘; // str1: eccs operation 2: change ‘c‘->‘e‘; // str1: eees operation 3: change ‘s‘->‘c‘; // str1: eeec return 3;
str1: accs, str2: efec return -1;
str1: abb , str2: baa
operation 1: change ‘a‘->‘*‘; // str1: *bb operation 2: change ‘b‘->‘a‘; // str1: *aa
accs -> efec: -1
abb -> baa: 3
可以看到如果想要convert成功所有的node的out degree要小于等于1才可以。答案是计算edges+cycle的数量。
Alien Dictionary
There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
Example 1:
Input:
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
Output: "wertf"
Example 2:
Input:
[
"z",
"x"
]
Output: "zx"
Example 3:
Input:
[
"z",
"x",
"z"
]
Output: ""
Explanation: The order is invalid, so return ""
.
Note:
-
You may assume all letters are in lowercase.
-
You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
-
If the order is invalid, return an empty string.
-
There may be multiple valid order of letters, return any one of them is fine.
Topological sort: similar with course schedule series
e.g. [ "wrt", "wrf", "er", "ett", "rftt" ]
1. wrt -> wrf: t -> f
2. wrt -> er: w -> e
3. er -> ett: r -> t
4. ett -> rftt: e -> r
e.g. [ "z", "x", "z" ] : 有环 -> invalid
以上是关于Graph题目总结不定期更新的主要内容,如果未能解决你的问题,请参考以下文章