Posts 英文字符串排序算法
Post
Cancel

英文字符串排序算法

编程工作偶尔会遇到一些不常见问题需要处理,学编程处理问题也难免需要熟悉一些算法

以前学习的时候就遇到过一个看似简单的排序算法问题,当时的解决办法是我没有用过的,在此记录一下’’

问题 - 英文字符串排序

如下几个英文单词或者字母

apple,car, a,family,sky,application,app,baby,back,background,bad,bbbbb,bee,cafe ,cake,care

排序后的结果是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
a
app
apple
application

baby
back
background
bad
bbbbb
bee
cafe 
cake
car
care
family
sky

**/

规则逻辑

通过结果可知

a 与 app a排前面 (开头字母相同,短的排在前面)

back 与 backgroud back排在前面 (开头字母相同,短的排在前面)

application 与 baby application 排在前面(开头字母不同,从a-z依次排序)

设计实现

a=1 b=2 c=3 d=4 e=5 f=6 g=7 h=8 i=9 j=10

k=11 l=12 m=13 n=14 o=15 p=16 q=17 r=18 s=19 t=20

u=21 v=22 w=23 x=24 y=25 z=26

a代表的是 1

b代表的是 2

z 代表 26 就可以实现初步排序

但是 bbbbb与 bee 两个单词要实现 bee 在前,逻辑该怎么写呢

起初想法是,字母依次比较,bbbbbbee比较的第二个字母的时候, be 分别代表 2 和 5 所以bbbbb排前面,问题是一个一个字母比较看起来很麻烦,10个单词,10个都要比较

有以下解决方案,都有用到递归

方法一 通过单词获取权重进行排序(当初使用方法)

bbbbb => b =2 b=2 b=2 b=2 b=2

bee => b = 2 e =5 e = 5

权重数 Px

Px(bbbbb) = 2 + 2 * 27^-1 + 2 * 27^-2 + 2 * 27^-3 + 2 * 27^-4 = 2.079

Px(bee) = 2 + 5 * 27^-1 + 5 * 27^-2 = 2.192

通过这个计算方式可以获得权重值

Px(bbbbb) < Px(bee)

所以 bbbbb 排在 baby 前面

权重数27

这里为什么是 27 不是26 是考虑到一种情况,会导致排序失败

比如 az 与 b比较

Px(az) = 1 + 26 * 26^-1 = 2

Px(b) = 2

Px(az) = Px(b) 显然是错的 将26 改为 27 就可避免这个错误

优点

不管是任何单词,一千个也好,得出每个字符串对应的权重值,就能做到排序

代码实现

更新与2020-01-09,后面做了优化,区分字母大小写,权重改为53

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public static void main(String[] args) {
    String[] noP = {"Baby","apple", "car", "A", "family", "B","b", "Sky", "application", "app", "baby", "back", "background",
                    "bad", "bbbbb", "bee", "cafe", "cake", "care" };
    String[] nopTop = sortByWeights(noP);
    for (String string : nopTop) {
        System.out.print(string + ",");
    }
    System.out.println();
    System.out.println("----------------------");
    for (String string : nopTop) {
        System.out.println("weights:\t" + getStrWeights(string,0) + "\t" + string);
    }
}


/**
 *  for 权重排序
 * 
 */
public static String[] sortByWeights(String[] disorder) {

    double[] weightsArr = new double[disorder.length]; 
    HashMap<Double,Integer> recordMap = new HashMap<>();

    // 计算每个字符串的权重值
    for (int i=0; i<disorder.length ;i++) {
        weightsArr[i] = getStrWeights(disorder[i],0);
        recordMap.put(weightsArr[i],i);//保存权重值对应的字符串所在数组位置
    }

    // 将获取的权重值排序
    Arrays.sort(weightsArr);

    String[] sorderStr = new String[disorder.length];
    int orderIndex = 0;
    for (int i=0; i<sorderStr.length ;i++) {
        // 拿出排好序的索引
        orderIndex = recordMap.get(weightsArr[i]);
        sorderStr[i] = disorder[orderIndex];
    }
    return sorderStr;
}

// 权重数值
private final static double weightsNum = 53;

/**
 * for 计算字符串的权重值算法
 * @param deep
 * @param str
 * @return weights
 */
public static double getStrWeights(String str,int deep) {
    int c = str.charAt(deep);

    boolean isUppercase = true;
    if(c >= 97) {
        c = c - 32;
        isUppercase = false;
    }
    c = c - 64; // A,a -> 1; B,b -> 2

    int molecular = c*2; 
    if(isUppercase) molecular--; //if(B) -> 3;if(b) -> 4; for end [Baby,baby]

    // 这里考虑了大小写 如果字母是B 权重=3/53 小写b 权重=4/53  使小大小写也能排序

    double weights =  molecular	/ (Math.pow(weightsNum, deep));


    return ++deep >= str.length() ? weights : weights + getStrWeights(str,deep); //递归到字符串末尾
}

运行main方法,控制台输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
A,app,apple,application,B,Baby,b,baby,back,background,bad,bbbbb,bee,cafe,cake,car,care,family,Sky,
----------------------
weights:	1.0	A
weights:	2.6151655393378426	app
weights:	2.615328013590046	apple
weights:	2.615329041941876	application
weights:	3.0	B
weights:	3.0394956910738395	Baby
weights:	4.0	b
weights:	4.0394956910738395	baby
weights:	4.040019613506452	back
weights:	4.0400214752701284	background
weights:	4.0405838376646495	bad
weights:	4.076923067174232	bbbbb
weights:	4.192239231043076	bee
weights:	6.042075001511314	cafe
weights:	6.045634987271372	cake
weights:	6.050551797792809	car
weights:	6.050618967335452	care
weights:	12.047115878410484	family
weights:	37.43289426842293	Sky

缺点

考虑到前一种算法的计算,如果单词长度超过20或者更长,会导致计算量很大的问题

如果有一百个单词,比较计算很有必要,如果只有两个单词

bbbbbbbbbbbbbbbb 与 bar 比较 用权重法不合适,因为只有两个单词没比较计算这么多,就能得出排序结论,下面就讲讲另一种排序算法

方法二 逐个字母计算排序

下面说一下新思路,逐个比较

apple,car, a,family,sky,application,app,baby,back,background,bad,bbbbb,bee,cafe ,cake,care

还是上面的单词

  1. 首先获取每个字符串的第一个字母

第一个字母为 a 的 全部取出

apple a application app

比较他们的第二个字母 a 没有第二个字母,自然排在最前面,依次类推,使用递归即可完成排序

因为临时想到的一种排序方法,用到了TreeSet HashMap ArrayList 工具类,感觉还可以后期优化。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package javabasis.algorithm;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

/**
 * 字段排序算法
 * 
 * @author Narule
 *
 */

public class StringAlgorithm {

	/**
	 * 逐个字母比较排序
	 * 
	 * @param disorder
	 * @return orderly
	 */
	public static String[] nopTop(String[] disorder) {
		int index = 0;
		int end = disorder.length;
		String[] orderly = new String[end]; // 新建排序后的数组
		TreeMap<Character, List<String>> treeMap = new TreeMap<>(); // 排序工具类,key是按照大小排序的
		List<String> list = null;

		// 收集字符串首字母信息
		for (String str : disorder) {
			char cTag = str.charAt(0);

			list = treeMap.get(cTag);
			if (list == null) {
				list = new ArrayList<>(1);
			}
			list.add(str);
			treeMap.put(cTag, list);
		}

		// 通过收集的首字母信息给字符串排序
		Set<Character> keySet = treeMap.keySet();
		for (char cTag : keySet) {
			list = treeMap.get(cTag);
			if (list != null && list.size() > 0) {

				if (list.size() < 2) { // 如果只有一个字符串,不需要递归
					for (String string : list) {
						orderly[index] = string;
						index++;
					}
				} else { // 如果有两个以上字符串,开头字母相同,可能需要递归排序
					ArrayList<String> arrayList = new ArrayList<>(0);
					for (String string : list) {
						if (string.length() > 1) { // 字符串长度大于2的,需要添加到list,准备下一次递归排序用到
							arrayList.add(string.substring(1));
						} else {
							orderly[index] = string;
							index++;
						}
					}
					if (arrayList.size() > 1) {
						String[] array = new String[arrayList.size()];
						int i = 0;
						for (String string : arrayList) {
							array[i] = string;
							i++;
						}
						array = nopTop(array); // 还需要递归排序 back background -> ack ackground
						for (String string : array) {
							orderly[index] = cTag + string;
							index++;
						}
					} else if (arrayList.size() == 1) {
						orderly[index] = cTag + arrayList.get(0);
						index++;
					}
				}
			}

		}
		treeMap.clear();
		return orderly; // 排序后的字符串数组
	}

	public static void main(String[] args) {
		String[] noP = { "apple", "car", "a", "family", "sky", "application", "app", "baby", "back", "background",
				"bad", "bbbbb", "bee", "cafe", "cake", "care" };
		String[] nopTop = nopTop(noP);
		for (String string : nopTop) {
			System.out.println(string);
		}

	}
}

此方法用到TreeMap,这是Java工具类,自带排序效果,对此有疑问可以查看java源代码,或介绍文档

优点

没有很大的计算量

缺点

使用TreeMap ArrayList 对象,递归过多也会出现内存损耗过大或者溢出的情况

未完,后期待优化

This post is licensed under CC BY 4.0 by the author.

SpringCloud-ServerConfig

四轴飞行器相关技术

Comments powered by Disqus.