使用 Java 中字符串单词中排序的字母创建新字符串
如何使用取自另一个字符串的字母顺序字母创建一个字符串?
假设我有这样的东西
String theWord = "Hello World";
我如何计算新字符串以使其看起来像“
德赫洛尔w
这是单词,但按字母顺序逐个字符排序。
提前致谢
How do I create a String with alphabetical order letters taken from another String?
Let's say I have something like this
String theWord = "Hello World";
How do I compute the new String to make it look like"
dehllloorw
Which is theWord but sorted character by character in alphabetical order.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
请参阅
Arrays.sort()
&toCharArray()< /代码>
See
Arrays.sort()
&toCharArray()
同意,我偷了解决方案。但显然,去除空格并使所有内容都小写也很重要:
Agreed, I stole the solution. But apparently, it's also important to strip whitespace and make everything lowercase:
上述解决方案都不是特定于区域设置的,因此我采用了这个解决方案,它效率不高,但效果很好。
None of the above solutions are locale specific , therefore I came with this solution, it is not efficient , but it works very well..
所有解决方案都是 O(nlogn),因为它们对数组进行排序。相反,我们可以采用 array[26] 并在 O(n) 内完成此操作。
将其转换为小写并删除 O(n) 的空格后,
int[] ar=新 int[26];
for(char c:s.toCharArray()) ar[c-'a']++;
然后形成所需的字符串 O(n)。
All the solutions were O(nlogn) as they are sorting the array. Instead we can take array[26] and do this in O(n).
after you covert it into lowercase and remove spaces which are O(n),
int[] ar=new int[26];
for(char c:s.toCharArray()) ar[c-'a']++;
and then form the required string O(n).