簡體   English   中英

在字符串中找到最長的連續字符串模式並將其刪除

[英]Finding longest continuous string patterns inside string and erasing it

我想知道既然找不到類似的主題,那么在字符串中找到連續的字符串模式並從中刪除它們的最佳方法是什么?

我的意思是:我有一個字符串:“ AAAAaaCCCCCCcDDDEEEE”,我想找到最長的相同連續字符串,因為C出現了6次,所以它將是CCCCCC,然后從字符串中刪除它,這樣我就得到了“ AAAAaacDDDEEEE”,然后一遍又一遍地執行,直到只有一個連續的字符串為止。 我已經嘗試過自己做,但是似乎需要花更多的代碼來完成其簡單性,

請幫忙

您可以找到連續的字符並替換為空字符串。

 var string = "AAAAaaCCCCCCcDDDEEEE", longest = string.match(/(.)\\1*/g).reduce((a, b) => a.length > b.length ? a : b); console.log(longest); string = string.replace(longest, ''); console.log(string); 

具有功能。

 function remove(string) { var longest = string.match(/(.)\\1*/g).reduce((a, b) => a.length > b.length ? a : b); while (longest.length > 1) { string = string.replace(longest, ''); longest = string.match(/(.)\\1*/g).reduce((a, b) => a.length > b.length ? a : b); } return string; } console.log(remove("AAAAaaCCCCCCcDDDEEEE")); 

另一個選擇只是老式的while循環。 與使用正則表達式相比,這將具有顯着更高的性能,但代價是更多的代碼和(少許)可讀性降低:

 let s = "AAAAaaCCCCCCCcDDDEEEE" let start = 0, max = 0, current = 0, maxStart = 0 while(current <= s.length) { if (s[current] !== s[start]){ if (current - start > max){ max = current - start maxStart = start } start = current } current++ } // the found string: console.log(s.substring(maxStart, maxStart+max)) // delete s = s.slice(0,maxStart) + s.slice(max + maxStart) console.log(s) 

您可以使用正則表達式來獲取鏈鏈數組。 使用Math.max()Array.map()獲得最長鏈的長度。 使用Array.filter()刪除最長鏈,並比合並回字符串Array.join()

這將處理多個相同長度的長鏈。

 const removeLongest = (str) => { const chains = str.match(/(.)\\1*/g); // get an array of chains const longest = Math.max(...chains.map(s => s.length)); // find the longest chain length return chains.filter(({ length }) => length !== longest) // remove longest chains .join(''); // convert array back to string }; console.log(removeLongest('AAAAaaCCCCCCcDDDEEEE')); // AAAAaacDDDEEEE console.log(removeLongest('AAAAaaCCCCCCcDDDEEEEEE')); // AAAAaacDDD 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM