首页 > 代码库 > Leetcode#165 Compare Version Numbers

Leetcode#165 Compare Version Numbers

原题地址

 

按"."分割,然后比较

需要注意的地方:

1. 多于的前缀0。例如"001"="1"

2. 多余的后缀版本号。例如"1"="1.0.0.0"

 

代码:

 1 int compareVersion(string version1, string version2) { 2   int last1 = -1; 3   int last2 = -1; 4   int i = 0; 5   int j = 0; 6   int k = 0; 7  8   while (i < version1.length() && j < version2.length()) { 9     // 切割10     while (i < version1.length() && version1[i] != .) i++;11     while (j < version2.length() && version2[j] != .) j++;12     string sub1 = last1 < 0 ? version1.substr(0, i) : version1.substr(last1 + 1, i - last1 - 1);13     string sub2 = last2 < 0 ? version2.substr(0, j) : version2.substr(last2 + 1, j - last2 - 1);14 15     // 去除前缀016     k = 0;17     while (k < sub1.length() - 1 && sub1[k] == 0) k++;18     sub1 = sub1.substr(k);19     k = 0;20     while (k < sub2.length() - 1 && sub2[k] == 0) k++;21     sub2 = sub2.substr(k);22 23     // 比较24     if (sub1.length() == sub2.length()) {25       for (int k = 0; k < sub1.length(); k++) {26         if (sub1[k] == sub2[k])27           continue;28         return sub1[k] > sub2[k] ? 1 : -1;29       }30       last1 = i++;31       last2 = j++;32     }33     else34       return sub1.length() > sub2.length() ? 1 : -1;35   }36 37   // 去除冗余后缀版本号38   while (i < version1.length() && (version1[i] == 0 || version1[i] == .))39     i++;40   while (j < version2.length() && (version2[j] == 0 || version2[j] == .))41     j++;42 43   if (i < version1.length())44     return 1;45   if (j < version2.length())46     return -1;47   return 0;48 }

 

Leetcode#165 Compare Version Numbers