如何对由大到小字母组成的字符串数组排序

it2025-05-26  12

  有一个由大到小字母组成的字符串,对它进行重新排序组合,使得其中的所有小写字母排在大写字母的前面(大写或小写字母之间不要保持次序)。

分析:

  可以使用类似快速排序的方法处理。用两个索引分别指向字符串的首和尾,首索引正向遍历字符串,找到一个大写字母,尾索引逆向遍历字符串,找到一个小写字母,交换两个索引的位置的字符,然后两个索引沿着相应的方向继续向前移动,重复上述步骤,直到首索引大于或等于尾索引为止。

实现代码:

package lock; public class T12 { public static void ReverseArray(char[] ch) { int len=ch.length; int begin=0; int end=len-1; char temp; while(begin<end) { //正向遍历找到下一个大写字母 while(ch[begin]>='a'&&ch[end]>begin) ++begin; //逆向遍历找到下一个小写字母 while(ch[end]>='A'&&ch[end]<='Z'&&end>begin) --end; temp=ch[begin]; ch[begin]=ch[end]; ch[end]=temp; } } public static void main(String[] args) { // TODO Auto-generated method stub char[]ch="MANBAout".toCharArray(); ReverseArray(ch); for(int i=0;i<ch.length;i++) { System.out.print(ch[i]); } } }

运行结果:

算法分析:

  这种方法对字符串只进行了一次遍历,因此,算法的时间复杂度为O(N),其中,N是字符串的长度。

最新回复(0)