追加和删除hackerrank的字符串

/* why the two test cases are not passed by this code*/ /*the link of the problem is 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";

}
点赞
评论
99.90%
99.90%

这是一个可行的解决方案,并在代码中添加了注释,以使您容易理解:

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";
}
点赞
评论