题目
代码(首刷看解析)
class Solution {
public:
int compareVersion(string version1, string version2) {
int start1 = 0, size1 = version1.size();
int start2 = 0, size2 = version2.size();
version1 += '.';
version2 += '.';
while(start1 < size1 || start2 < size2) {
int next1 = find(version1.begin() + start1, version1.end(), '.') - version1.begin();
int next2 = find(version2.begin() + start2, version2.end(), '.') - version2.begin();
int s1 = atoi(&*version1.begin() + start1); // 自动去除后面不规则的字符串 加号优先级更高
int s2 = atoi(&*version2.begin() + start2);
if(s1 == s2) {
start1 = next1 + 1; // 移动到下一个 '.'后面的数字
start2 = next2 + 1;
} else {
return s1 > s2 ? 1 : -1;
}
}
return 0;
}
};
总结:
- 掌握
atoi
,这个函数可以自动去除后面不规则的字符串,去除前置0。 - 掌握
iterator
之间的运算。
代码(8.13 二刷看解析)
func compareVersion(version1 string, version2 string) int {
m, n := len(version1), len(version2)
i, j := 0, 0
for i < m || j < n {
x, y := 0, 0
for ; i < m && version1[i] != '.'; i++ {
x = x*10 + int(version1[i]-'0')
}
i++
for ; j < n && version2[j] != '.'; j++ {
y = y*10 + int(version2[j]-'0')
}
j++
if x > y {
return 1
} else if x < y {
return -1
}
}
return 0
}
class Solution {
public:
int compare(string version1, string version2) {
int i = 0, j = 0;
int m = version1.size(), n = version2.size();
version1 += '.';
version2 += '.';
while(i < m || j < n) {
int next1 = find(version1.begin() + i, version1.end(), '.') - version1.begin();
int next2 = find(version2.begin() + j, version2.end(), '.') - version2.begin();
int sub1 = atoi(&*(version1.begin()+i));
int sub2 = atoi(&*(version2.begin()+j));
if(sub1 == sub2) {
i = next1 + 1;
j = next2 + 1;
} else {
return sub1 > sub2 ? 1 : -1;
}
}
return 0;
}
};