165. Compare Version Numbers

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

思路:
这个是String转Int来计算,务必想到用char来跟'0'或者'a' 或者'A'进行计算。
由于存在".",我们可以分成"."之前的版本跟"."之后的版本来分开计算, 因为会出现1.0 == 1情况。
这个题目如果用split会使程序跑起来会很慢。

public class Solution {
    public int compareVersion(String version1, String version2) {
        int p1 = 0; // pointer in version1
        int p2 = 0; // pointer in version2

        while(p1 < version1.length() || p2 < version2.length()) {
            int v1 = 0;
            int v2 = 0;

            while(p1 < version1.length() && version1.charAt(p1) != '.') {
                v1 = v1 * 10 + version1.charAt(p1) - '0';
                p1++;
            }
            while(p2 < version2.length() && version2.charAt(p2) != '.') {
                v2 = v2 * 10 + version2.charAt(p2) - '0';
                p2++;
            }
            p1++;
            p2++;
            if (v1 > v2) {
                return 1;
            } else if(v1 < v2) {
                return -1;
            }
        }

        return 0;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s