JAVA字符串混合排序,解决11在2前面的问题

参考博客:https://blog.csdn.net/zzm628/article/details/81189574?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control

import java.util.Comparator;

/**
 * 字符串混合排序
 */
public class StringComparator implements Comparator<String> {

	@Override
	public int compare(String o1, String o2) {
		if (o1.equals(o2)) {
			return 0;
		}
		int i = 0, j = 0;
		String temp1, temp2;
		int sum1, sum2;
		int len1 = o1.length();
		int len2 = o2.length();
		int length = Math.min(len1, len2);
		while (i < length && j < length) {
			temp1 = "";
			temp2 = "";
			// 1、当前位置不是数字,要么区分大小,要么相等循环继续
			if (o1.charAt(i) > '9' || o1.charAt(i) < '0' || o2.charAt(j) > '9'
					|| o2.charAt(j) < '0') {
				if (o1.charAt(i) == o2.charAt(j)) {
					i++;
					j++;
					continue;
				} else if (o1.charAt(i) > o2.charAt(j)) {
					return 1;
				} else {
					return -1;
				}
			}
			// 2、当前位置是数字,继续取后几位的数字,拼成字符串
			while (i < len1 && o1.charAt(i) <= '9' && o1.charAt(i) >= '0') {
				temp1 += o1.charAt(i);
				i++;
			}
			while (j < len2 && o2.charAt(j) <= '9' && o2.charAt(j) >= '0') {
				temp2 += o2.charAt(j);
				j++;
			}
			// 计算字符串中数字的数值
			sum1 = calculate(temp1);
			sum2 = calculate(temp2);
			// 如果数值相等,要么长度一致,那么i==j,循环继续;
			// 要么长度不一致,长度较长的字符串前面是0,以0开头的放前面
			if (sum1 == sum2) {
				if (temp1.length() < temp2.length()) {
					return 1;
				} else if (temp1.length() > temp2.length()) {
					return -1;
				} else {
					continue;
				}
			} else if (sum1 > sum2) {
				return 1;
			} else {
				return -1;
			}
		}
		// 超过较小长度,未判断出谁大谁小,即较长者放后面
		return len1 > len2 ? 1 : -1;
	}

	/**
	 * 计算字符串数字的数值
	 * 
	 * @param str
	 * @return
	 */
	private int calculate(String str) {
		// 这里要小心,需要判断有效性
		if (str == null || str.length() == 0) {
			return 0;
		}
		int len = str.length();
		double sum = 0;
		int sign = 1;
		int j = 0;
		// 剔除字符串前方的空格
		while (str.charAt(j) == ' ') {
			j++;
		}
		// 判断正数和负数
		if (str.charAt(j) == '+') {
			sign = 1;
			j++;
		} else if (str.charAt(j) == '-') {
			sign = -1;
			j++;
		}
		// 计算剩余字符串
		for (int i = j; i < len; i++) {
			char current = str.charAt(i);
			if (current >= '0' && current <= '9') {
				sum = sum * 10 + (int) (current - '0');
			} else {
				// 碰到非数字,退出转换
				break;
			}
		}
		sum = sum * sign;
		// 这里要小心,需要判断范围
		if (sum > Integer.MAX_VALUE) {
			sum = Integer.MAX_VALUE;
		} else if (sum < Integer.MIN_VALUE) {
			sum = Integer.MIN_VALUE;
		}
		return (int) sum;
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值