JavaScript-在给定的字符串中删除具有时间复杂性o(n)和空间复杂性的替代重复字符的最佳方法是O(1)



在javaScript中,删除给定字符串中替代重复字符的最佳方法是与时间复杂性o(n),空间复杂性是o(1)?

//示例:输入:"你有美丽的眼睛"//输出:"您有Btiful ES"

您可以服用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);

最新更新