【问题标题】:How to make p consective characters by making k swaps in a String?如何通过在字符串中进行 k 交换来制作 p 个连续字符?
【发布时间】:2017-03-12 08:50:04
【问题描述】:

有一个1's0's 的字符串,例如110001110。我给了两个数字kp,我必须检查我是否可以通过k交换和交换我的意思是如果它是1然后将其设为0,反之亦然。

编辑-我想我还没有清楚地解释。 例如,让字符串为1110000111,让p = 3k = 1。所以我可以通过 1 次交换获得最多 3 个连续的 1's0's 答案是 yes 因为我可以将其更改为 1110010111

【问题讨论】:

  • 这是一道作业题吗?
  • 您可以进行 0 次交换吗?即使k > 0.
  • 尝试竞争性编程是件好事。现在,尝试自己解决而不是作弊。 (本题来自ongoing online competition
  • @amit 是的,先生,我知道这是来自在线编码竞赛,并且在提出这个问题之前我已经提交了正确的解决方案。实际上,我的解决方案是 O(nlogn) 并且有点用钩子或骗子。我想知道一种更好的方法,而 tbh 教程从来没有帮助过。干杯!

标签: arrays string algorithm


【解决方案1】:

您可以通过简单的循环在线性时间内完成此操作。在检测到全 0 或全 1 的单调序列后,您将使用一个简单的公式计算需要多少次翻转。除了 p 为 1 的情况外,这些翻转始终可以使该序列的外部数字保持不变。在这种情况下,必须进行翻转以获得 01010101。 .. 或者 101010101.. 也可以通过简单的模表达式来完成。然后将采取两者中最好的(交换次数减少)。

这是一个 JavaScript 实现,其中包含两个示例运行,用于一般情况 (p > 1) 和提到的特殊情况 (p = 1):

function swapsForMaxSequence(s, maxSize) {
    var head, tail, swaps;

    if (maxSize < 1) return false;
    
    swaps = 0;
    if (maxSize === 1) { // Special case
        // 0 and 1 should be alternating:
        for (head = 0; head < s.length; head++) { // n iterations
            if (Number(s[head]) == head % 2) swaps++;
        }
        // Either the made swaps or the opposite swaps would do it:
        return Math.min(swaps, s.length - swaps);
    }
    tail = 0;
    for (head = 1; head <= s.length; head++) { // n iterations
        if (head === s.length || s[head] != s[tail]) { // end of sequence?
            swaps += Math.floor((head - tail)/(maxSize+1));
            tail = head; // Start of new sequence
        }
    }
    return swaps;
}

// Sample input:
var s = '10110101010', // Special case
    k = 1,
    p = 1;

// Display input:
console.log('s:', s, 'k:', k, 'p:', p);

// Run the algorithm
result = swapsForMaxSequence(s, p);

// Display outcome:
console.log('result:', result);

// Second sample:
var s = '1110000111', // Special case
    k = 1,
    p = 3;

// Display input:
console.log('s:', s, 'k:', k, 'p:', p);

// Run the algorithm
result = swapsForMaxSequence(s, p);

// Display outcome:
console.log('result:', result);

【讨论】:

  • 很抱歉问题中的信息不完整。我已经编辑过了。
  • 我根据这一澄清重写了我的答案。
  • 请注意,这个问题来自ongoing online competition。请避免帮助 OP 获得相对于其他参与者的不公平优势。
  • @trincot 非常感谢先生!你的逻辑比我好很多,代码是我写的1/3。
猜你喜欢
  • 2020-02-27
  • 2017-04-03
  • 2019-08-14
  • 2021-12-01
  • 2018-04-25
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多