简体   繁体   English

Javascript - 在时间复杂度为 O(n) 且空间复杂度为 O(1) 的给定字符串中删除交替重复字符的最佳方法是什么?

[英]Javascript - What is the best way to remove alternate repeating character in a given string with time complexity O(n) and Space Complexity was O(1)?

In Javascript, What is the best way to remove alternate repeating character in a given string with time complexity O(n) and Space Complexity was O(1)?在 Javascript 中,删除给定字符串中时间复杂度为 O(n) 且空间复杂度为 O(1) 的交替重复字符的最佳方法是什么?

// Example: Input: “you have beautiful eyes” // Output: ”you have btiful es” // 示例:输入:“you have beautiful eyes” // 输出:“you have btiful es”

You could take a Set and remove visited characters and use a Set for visited characters in a word, then take that character.您可以使用Set并删除访问过的字符,并对单词中的访问过的字符使用Set ,然后使用该字符。

you have beautiful eyes    string
-----------------------    ------------------------------
   _    _         _        keep spaces
you have b   tif l    s    filtering with visited
                     e     additional filtering with word
you have b   tif l   es    result

 var string = 'you have beautiful eyes', visited = new Set, word = new Set, result = Array .from(string, c => c === ' ' && (word = new Set) || !visited.has(c) && visited.add(c) || word.has(c) || !word.add(c) ? c : '' ) .join(''); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM