/ *为什么两个测试用例没有通过此代码传递* // *问题的链接是https://www.hackerrank.com/challenges/append-and-delete/problem * /
static String appendAndDelete(String s, String t, int k) {
if (s.length() + t.length() < k)
return "Yes";
int commonlength = 0;
for (int i = 0; i < Math.min(s.length(), t.length()); i++) {
if (t.charAt(i) == s.charAt(i))
commonlength++;
else
break;
}
if ((k - s.length() - t.length() + 2 * commonlength) % 2 == 0) {
return "Yes";
}
return "No";
}
非常简单。这是通过所有提到的测试用例的解决方案:
static String appendAndDelete(String s, String t, int k) {
if (s.equals(t))
return (k >= s.length() * 2 || k % 2 == 0) ? "Yes" : "No";
int commonlength = 0;
for (int i = 0; i < Math.min(s.length(), t.length()); i++) {
if (t.charAt(i) != s.charAt(i))
break;
commonlength++;
}
int cs = s.length() - commonlength;
int ct = t.length() - commonlength;
int tot = cs + ct;
return ((tot == k) || (tot < k && (tot - k) % 2 == 0) || (tot + (2 * commonlength) <= k)) ? "Yes" : "No";
}
您需要在代码中再添加一个条件,因为以下条件还不够:
(k - s.length() - t.length() + 2 * commonlength) % 2 == 0
尝试一下:
int balance = k - s.length() - t.length() + 2 * commonlength;
if (balance >= 0 && (balance) % 2 == 0) {
return "Yes";
}
您需要再加上一个附加条件:balance >= 0
如上所述。
这里是一个可以通过所有测试用例的可行解决方案,并在代码中添加了注释以便清晰理解:
static String appendAndDelete(String s, String t, int k) {
// Check if k is greater or equal to both the lengths
if (s.length() + t.length() <= k)
return "Yes";
int commonlength = 0;
// Get the common matching character length
for (int i = 0; i < Math.min(s.length(), t.length()); i++) {
if (t.charAt(i) == s.charAt(i))
commonlength++;
else {
break;
}
}
// count how many modifications still needed
int balance = s.length() - commonlength;
balance += t.length() - commonlength;
// Check if k is greater than balance count
if (balance <= k) {
// Special case, we need to perform exactly k operations
// so if balance is odd then k should be odd, if balance is even
// then k must be even.
if ((balance - k) % 2 == 0) {
return "Yes";
}
}
return "No";
}