#include<iostream> #include<cstdio> #include<string> #include<algorithm> using namespace std; int main() { string str; while(cin >> str) { sort(str.begin(), str.end()); cout << str << endl; } return 0; }
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); String str=sc.nextLine(); char[] s=str.toCharArray(); quicksort(s,0,s.length-1); String res=new String(s); System.out.print(res); } private static void quicksort(char[] sort,int left,int right){ if(left<right){ int mid=partition(sort,left,right); quicksort(sort,left,mid-1); quicksort(sort,mid+1,right); } } private static int partition(char[] sort,int left,int right){ char tmp=sort[left]; while(left<right){ while(left<right&&sort[right]>tmp){ right--; } if(left<right){ sort[left]=sort[right]; left++; } while(left<right&&sort[left]<tmp){ left++; } if(left<right){ sort[right]=sort[left]; right--; } } sort[left]=tmp; return left; } }
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); char[] array = scanner.nextLine().toCharArray(); Arrays.sort(array); for (char c : array) { System.out.print(c); } } }
#include <stdio.h> #include <algorithm> #include <string.h> using namespace std; int main() { char array[30]; while (EOF != scanf("%s", array)) { sort(array, array + strlen(array)); printf("%s\n", array); } return 0; }
#include<iostream> #include<string> #include<algorithm> using namespace std; int main() { string str; cin>>str; int m[20]; for(int i=0;i<str.size();++i) { m[i]=str[i]; } sort(m,m+str.size()); for(int i=0;i<str.size();++i) { str[i]=m[i]; } cout<<str; return 0; }
使用C语言中的qsort
#include <stdio.h> #include <string.h> int cmp(const void* a, const void* b) { return *(char*) a - *(char*) b; } int main() { char* data = calloc(21, sizeof(char)); scanf("%s", data); qsort(data, strlen(data), sizeof(char), cmp); int i; for (i = 0; i < strlen(data); i++) { printf("%c", data[i]); } return 0; }
运行时间:45ms
占用内存:10712k
一开始自以为是的用TreeSet做(其实是想得太多想的复杂化了,用以下代码不是很简单的吗 也许效率会低一些)
发现通过率11%
哦原来测试用例中有重复字符
在输出时重复字符亦需要输出
然而Set是不允许有重复元素的。
finally, the code is:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(scan.hasNext()) {
String str = scan.nextLine();
char[] arr = str.toCharArray();
for(int i = 0; i < arr.length - 1; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
Character biggerOne = arr[i];
arr[i] = arr[j];
arr[j] = biggerOne;
}
}
}
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
}
}
#include<iostream> #include <string> using namespace std; int main() { string str; while (cin>>str) { for (int i = 0; i < str.length(); i++) for(int j = 0; j < str.length() - i - 1; j++) { if(str[j+1] < str[j]) { char temp = str[j+1]; str[j+1] = str[j]; str[j] = temp; } } cout<<str<<endl; } return 0; }