Leetcode-165
如題,這種題目首先要作的確定是按'.'分割字符串。下面是我總結的兩種分割字符串的方法。
首先,使用istringstream和getline進行分割:code
string version1 = "1.0.0.1"; vector<int> v1; istringstream s1(version1); string temp; while(getline(s1,temp,'.')){ v1.push_back(stoi(temp)); }
其次,還有一個傻瓜辦法:leetcode
string version1 = "1.0.0.1"; vector<int> v1; string temp; for(int i = 0;i<version1.size();++i){ if(version1[i] != '.') temp += version[i]; else{ v1.push_back(stoi(temp)); temp.clear(); } } if(temp != "") v1.push_back(stoi(temp));
下面附上該題的方法:字符串
class Solution { public: int compareVersion(string version1, string version2) { vector<int> v1,v2; istringstream s1(version1); istringstream s2(version2); string temp; while(getline(s1,temp,'.')){ v1.push_back(stoi(temp)); } while(getline(s2,temp,'.')){ v2.push_back(stoi(temp)); } while(v1.size()>v2.size()){ v2.push_back(0); } while(v1.size()<v2.size()){ v1.push_back(0); } for(int i = 0;i<v1.size();++i){ if(v1[i] > v2[i]){ return 1; } if(v1[i] < v2[i]){ return -1; } } return 0; } };