Fix:7-修复Solution7的bug,并添加测试类。#419
Open
Peek-A-Boo-1202 wants to merge 1 commit into
Open
Conversation
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.
学号2023112947。
修改思路:
问题分析与BUG定位
这段代码的思路是正确的:
但在实现过程中,存在以下几个BUG:
UnionFind unionFind = new UnionFind(len-1);
如果字符串s的长度是len,那么它的索引范围是0到len-1。并查集需要管理len个元素,所以它的构造函数应该传入len,而不是 len-1。
if (pairs.size() <= 1) { return s; }
这个条件判断是错误的。
如果 pairs.size() == 1,例如 s = "ba", pairs = [[0,1]],那么s 应该变成 "ab"。但当前代码会直接返回 "ba",这是不正确的。
实际上,即使 pairs为空,后续的并查集逻辑也能正确处理:所有元素都是独立的连通分量,字符会被原样放回,所以这个初始判断可以移除,让通用逻辑来处理。
stringBuilder.append(" ");
在构建最终结果字符串时,每次append一个字符后,又 append了一个空格。这显然与题目要求返回字典序最小的字符串不符,会产生带有空格的错误结果。