乐趣区

造轮子-分割字符串

Leetcode-165
如题,这种题目首先要做的肯定是按 ’.’ 分割字符串。下面是我总结的两种分割字符串的方法。
首先,使用 istringstream 和 getline 进行分割:

string version1 = "1.0.0.1";
vector<int> v1;
istringstream s1(version1);
string temp;

while(getline(s1,temp,'.')){v1.push_back(stoi(temp));
}

其次,还有一个傻瓜办法:

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;
    }
};
退出移动版