关闭

Compare Version Numbers

标签: Javaleetcode
112人阅读 评论(0) 收藏 举报
分类:

1 题目描述

Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37
题目出处:https://leetcode.com/problems/compare-version-numbers/

2 解题思路

“.”将两个数字分割开,只需要比较相同位置上的两个数字的大小即可。如果相同,则比较下一个,直到不相同(或者没有)为止。有个特殊情况(“1.0”与“1”相等)。

3 相关知识

1.将数组转化为List的方法(将其作为参数传进去)为:
String[] v1s = version1.split("\\.");
ArrayList<String> alv1 = new ArrayList<String>(Arrays.asList(v1s));
2.字符串的split()方法的使用情况参照网址:http://www.cnblogs.com/mingforyou/archive/2013/09/03/3299569.html

4 源代码

package com.larry.easy;

import java.util.ArrayList;
import java.util.Arrays;

public class CompareVersionNumbers {
	public int compareVersion(String version1, String version2) {
		String[] v1s = version1.split("\\.");
		String[] v2s = version2.split("\\.");
		ArrayList<String> alv1 = new ArrayList<String>(Arrays.asList(v1s));
		ArrayList<String> alv2 = new ArrayList<String>(Arrays.asList(v2s));
		
		//如果两个数组的个数不相同,较少的补零
		int num = v1s.length - v2s.length;
		if(num > 0){
			for(int i = 0; i < num; i++) alv2.add("0");
		}else if(num < 0){
			for(int i = 0; num < 0; num++) alv1.add("0");
		}
		
		int size = alv1.size();
		for(int i = 0; i < size; i++){
			int first = Integer.parseInt(alv1.get(i));
			int secd = Integer.parseInt(alv2.get(i));
			if(first > secd) return 1;
			else if(first < secd) return -1;
		}
		return 0;
    }
	public static void main(String[] args) {
		String s1 = "0.1";
		String s2 = "1.1";
		String s3 = "0.1.0";
		String s4 = "1";
		String version1 = s4;
		String version2 = s2;
		System.out.println(new CompareVersionNumbers().compareVersion(version1, version2));
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:26702次
    • 积分:693
    • 等级:
    • 排名:千里之外
    • 原创:108篇
    • 转载:5篇
    • 译文:0篇
    • 评论:0条
    文章分类