<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>String on Yosgi</title><link>https://yosgi.github.io/zh/tags/string/</link><description>Recent content in String on Yosgi</description><generator>Hugo</generator><language>zh</language><lastBuildDate>Mon, 29 Jun 2026 09:20:52 +0000</lastBuildDate><atom:link href="https://yosgi.github.io/zh/tags/string/index.xml" rel="self" type="application/rss+xml"/><item><title>1202-交换字符串中的元素</title><link>https://yosgi.github.io/zh/post/1202-%E4%BA%A4%E6%8D%A2%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84%E5%85%83%E7%B4%A0/</link><pubDate>Tue, 06 Jul 2021 00:00:00 +1200</pubDate><guid>https://yosgi.github.io/zh/post/1202-%E4%BA%A4%E6%8D%A2%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84%E5%85%83%E7%B4%A0/</guid><description>主要是用来学习并查集的思路，看了答案才下手的。 思路就是先对可交换的字符串进行分组，分组排序之后再组合起来 并查集就是用递归或者while循环实现find ， 然后 再用数组和下标的方式实现union var smallestStringWithSwaps = function(s, pairs) { var fa = [] var find = function (x) { if (x === fa[x]) { return x } else { return fa[x] = find(fa[x]) } } for (let i = 0; i &lt; s.length; i++) { fa[i] = i } for(let i = 0 ; i &lt; pairs.length ; i ++) { const [x,y] = pairs[i] fa[find(x)] = find(y) } var n = s.length // 计算分组后的map const vec = new Array(n).fill(0).map(() =&gt; new Array()); for (let i = 0; i &lt; n; i++) { fa[i] = find(i); vec[fa[i]].push(s[i]); } console.log(fa) // 对分组后的map 进行排序 for (let i = 0; i &lt; n; ++i) { if (vec[i].length &gt; 0) { vec[i].sort((a, b) =&gt; a.charCodeAt() - b.charCodeAt()); } } // 组合成ans const ans = new Array(n).fill(0); for (let i = 0; i &lt; n; ++i) { var group = fa[i] if ( group!= undefined &amp;&amp; vec[group].length) { // 取出每个组中序号最小的 ans[i] = vec[fa[i]].shift() } else { ans[i] = s[i] } } return ans.join('') };</description></item></channel></rss>