【发布时间】:2020-04-27 17:48:12
【问题描述】:
问题说明:Sherlock and the Valid String
此代码通过了所有正确性测试,15/20,但是,由于时间限制,一些测试失败了。
什么是让代码更快的好习惯?如何避免for 循环?
static String isValid(String s) {
String yesOrNo;
//Step 1: count the frequency of each char and out in a map <char, number>
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
int count = 0;
for (int c = 0; c < s.length(); c++) {
if (s.charAt(c) == s.charAt(i))
count++;
}
map.put(s.charAt(i), count);
}
//Step2: add all the numbers of occurrences of each char into a list
List<Integer> values = new ArrayList<>();
for (Map.Entry<Character, Integer> kv : map.entrySet()
) {
values.add(kv.getValue());
}
//Step 3: find the benchmark number
Map<Integer, Integer> occurPairs = new TreeMap<>();
for (int i = 0; i < values.size(); i++) {
occurPairs.put(values.get(i), Collections.frequency(values, values.get(i)));
}
Map.Entry<Integer, Integer> popVal = Collections.max(occurPairs.entrySet(), Map.Entry.comparingByValue());
Map.Entry<Integer, Integer> smallest = Collections.min(occurPairs.entrySet(), Map.Entry.comparingByValue());
//Step 4: compare each value with the benchmark
int numOfWrong = 0;
for (Integer value : values) {
if (!value.equals(popVal.getKey()))
numOfWrong += Math.abs(popVal.getKey() - value);
}
if (occurPairs.size() == 2 && smallest.getValue() == 1 && smallest.getKey() == 1)
yesOrNo = "YES";
else if (numOfWrong > 1)
yesOrNo = "NO";
else
yesOrNo = "YES";
System.out.println(yesOrNo);
return yesOrNo;
}
【问题讨论】:
-
我认为您正在做很多额外的工作来检查字符串是否无效。如果任何其他频率相差超过 1,则您可以立即返回 false,无需额外比较。
-
你知道什么是 Big-O 复杂度吗?如果不是,我们可以在答案中解释。
-
@NomadMaker HR 希望我返回一个字符串。 my 代码没有真正的其余部分,因为这是我输入的唯一方法,然后 HR 完成其余部分。
-
@JohnKugelman 这将非常有帮助。如果您有时间解释,我想学习一些新内容。
-
@Tyberius 我不同意“任何”,如果您阅读要求,它表示如果字符串的所有字符出现相同的次数,Sherlock 认为该字符串是有效的。如果他可以仅删除字符串中 1 个索引处的 1 个字符,并且其余字符将出现相同的次数,这也是有效的。给定一个字符串,判断它是否有效。如果是,则返回 YES,否则返回 NO。
标签: java performance optimization