simple yet challenging problem.

agolangf · · 499 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Well, I couldn&#39;t solve this one beautifully, so I wanted to see how better gophers would solve it</p> <p>consider the following slice:</p> <pre><code>[]string{&#34;one&#34;, &#34;two&#34; `&#34;three`, &#34;four&#34;, `five&#34;`} </code></pre> <p>convert that to the following:</p> <pre><code>[]string{&#34;one&#34;, &#34;two&#34;, &#34;three four five&#34;} </code></pre> <hr/> <p>other examples:</p> <p><strong>IN</strong></p> <pre><code>[]string{`&#34;one`, `two&#34;`, &#34;three&#34;} </code></pre> <p><strong>OUT</strong></p> <pre><code>[]string{&#34;one two&#34;, &#34;three&#34;} </code></pre> <hr/> <p><strong>IN</strong></p> <pre><code>[]string{&#34;one&#34;, `&#34;two&#34;`} </code></pre> <p><strong>OUT</strong></p> <pre><code>[]string{&#34;one&#34;, &#34;two&#34;} </code></pre> <hr/> <p><strong>IN</strong></p> <pre><code>[]string{&#34;one&#34;, `&#34;two`, &#34;three&#34;, &#34;four&#34;, &#34;five&#34;, `six&#34;`} </code></pre> <p><strong>OUT</strong></p> <pre><code>[]string{&#34;one&#34;, &#34;two three four five six&#34;} </code></pre> <p>you get the idea.</p> <hr/>**评论:**<br/><br/>jasonmoo: <pre><p><a href="http://play.golang.org/p/BWtiiPJ1M3">http://play.golang.org/p/BWtiiPJ1M3</a></p></pre>pyThat: <pre><p>great solution, you win !</p></pre>srtkkou: <pre><p>How about something like this? <a href="https://play.golang.org/p/TzB-qochQM">https://play.golang.org/p/TzB-qochQM</a></p></pre>pyThat: <pre><p>Kudos for that solution, you still lose a point tho for allocating a new slice</p></pre>daveddev: <pre><p>I am not a clever man. <a href="http://play.golang.org/p/wTrNtFdnmI" rel="nofollow">http://play.golang.org/p/wTrNtFdnmI</a></p></pre>daveddev: <pre><p>Ah, hahah. The backticks went right over my head. I&#39;ll try again when I get a moment.</p></pre>daveddev: <pre><p>This is what I believe to be a good balance between speed, reduced allocations, and maintainability. <a href="http://play.golang.org/p/hjDV7KZ9HH" rel="nofollow">http://play.golang.org/p/hjDV7KZ9HH</a></p></pre>djherbis: <pre><p>I don&#39;t know if I would call this clever, but it&#39;s fairly short :P</p> <p><a href="https://play.golang.org/p/DZlkOFb4-X" rel="nofollow">https://play.golang.org/p/DZlkOFb4-X</a></p> <p>(one slightly clever part is that the returned slice is actually the original slice, just modified, and it&#39;ll never grow that slice, this might not be considered clever if you don&#39;t like that it is &#34;destructive&#34; but that could easily be fixed with a copy).</p></pre>pyThat: <pre><p>it is clever that you used the same slice, but it is fairly complicated to follow.

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

499 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传