题解 | #比较版本号#
比较版本号
https://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
将版本号转成vector去做来得更加方便与直接,code say。
class Solution { public: vector<int> stringtoVector(string& v) { if(v.size() == 0) return {}; vector<int> res; int temp = -2; for(int i = 0; i < v.size(); i++) { if(v[i] == '.') { if(temp != -2) res.push_back(temp); temp = -2; res.push_back(-1); } else if(v[i] >= '0' && v[i] <= '9') { if(temp == -2) temp = 0; temp = temp*10 + v[i] - '0'; } else{} } if(temp != -2 && temp != 0) res.push_back(temp); temp = -2; return res; } int compare(string version1, string version2) { int iver1 = 0; int iver2 = 0; //转换成数组去做,.可以忽略或者按-1去写 vector<int> m_vecVer1 = stringtoVector(version1); vector<int> m_vecVer2 = stringtoVector(version2); //确保至少有一个达到了数组边界 while(iver1 < m_vecVer1.size() && iver2 < m_vecVer2.size()) { if(m_vecVer1[iver1] < m_vecVer2[iver2]) { return -1; } else if(m_vecVer1[iver1] > m_vecVer2[iver2]) { return 1; } else if(m_vecVer1[iver1] == m_vecVer2[iver2]) { iver1++; iver2++; } else{} } //对于没有达到数组边界的,直接与0比较即可,若是v1的值大于0,则返回1 if(iver1 < m_vecVer1.size() - 1) { for(int i = iver1 + 1; i < m_vecVer1.size(); i++) { if(m_vecVer1[i] > 0) return 1; } } if(iver2 < m_vecVer2.size() - 1) { for(int i = iver2 + 1; i < m_vecVer2.size(); i++) { if(m_vecVer2[i] > 0) return -1; } } //当所有条件都不满足时,说明该版本号码是保持一致的 return 0; } };