如何使用取自另一个字符串的字母顺序创建一个字符串?
假设我有这样的东西
String theWord = "Hello World";
如何计算新字符串以使其看起来像“
德鲁洛
这是 theWord,但按字母顺序逐个字符排序。
提前致谢
如何使用取自另一个字符串的字母顺序创建一个字符串?
假设我有这样的东西
String theWord = "Hello World";
如何计算新字符串以使其看起来像“
德鲁洛
这是 theWord,但按字母顺序逐个字符排序。
提前致谢
char[] chars = theWord.toCharArray();
Arrays.sort(chars);
String newWord = new String(chars);
同意,我偷了解决方案。但显然,去除空格并使所有内容小写也很重要:
char[] array = theWord.replaceAll("\\s+", "").toLowerCase().toCharArray();
Arrays.sort(array);
System.out.println(new String(array));
上述解决方案都不是特定于语言环境的,因此我提出了这个解决方案,它效率不高,但效果很好..
public static String localeSpecificStringSort(String str, Locale locale) {
String[] strArr = new String[str.length()];
for(int i=0;i<str.length();i++){
strArr[i] = str.substring(i,i+1);
}
Collator collator = Collator.getInstance(locale);
Arrays.sort(strArr, collator);
StringBuffer strBuf = new StringBuffer();
for (String string : strArr) {
strBuf.append(string);
}
return strBuf.toString();
}
char[] arr = new char[theWord.length()];
for(int i=0;i<theWord.length;i++)
{
arr[i]=theWord.charAt(i);
}
for(int i=0;i<theWord.length();i++)
for(int j=0;j<theWord.length();j++)
{
char temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
int size=theWord.length();
theWord="";
for(int i=0;i<size;i++)
{
theWord+=arr[i];
}
import java.util.Arrays;
import java.util.Scanner;
// re arrange alphabets in order
public class RearrangeAlphabets {
@SuppressWarnings("resource")
public static void main(String[] args) {
String theWord;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to rearrange: \n");
theWord = in.nextLine();
int length = theWord.length();
System.out.println("Length of string: "+length);
char[] chars=theWord.toCharArray();
Arrays.sort(chars);
String newWord=new String(chars);
System.out.println("The Re-Arranged word : "+newWord);
}
}
char[] chars2 = b.toLowerCase().toCharArray();
Arrays.sort(chars1);
String Ns1 = new String(chars1);
所有解决方案都是 O(nlogn),因为它们正在对数组进行排序。相反,我们可以使用 array[26] 并在 O(n) 中执行此操作。将其转换为小写并删除 O(n), int[] ar=new int[26]; for(char c:s.toCharArray()) ar[c-'a']++; 然后形成所需的字符串 O(n)。