码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode笔记】Compare Version Numbers

时间:2015-03-09 09:25:30      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:c++   stringstream   getline   leetcode   

    int compareVersion(string version1, string version2) {
        stringstream s1(version1), s2(version2);
        while(1){
            int i1= 0, i2 = 0;
            if(getline(s1, version1, '.'))   //if读取成功,将字符串convert为整型  
                i1 = stoi(version1);         //else读取失败,i1 i2还为0
            if(getline(s2, version2, '.')) 
                i2 = stoi(version2);   
            
            //如果s1 s2同时被读完,说明两字符串相等
            if(!s1 && !s2) //getline()返回值为false:本次读取失败,即上次读取已经extract完了
                return 0;  //getline()返回值为true:本次读取成功,但本次可能已经extract完了
            //不相等的字符串,会在这里给出判断
            if(i1 != i2)
                return i1 > i2 ? 1 : -1;               
        }         
    }

本题解决了对于getline()的几个疑点:

1. getline()作用

(1)
istream& getline (istream& is, string& str, char delim);
(2)
istream& getline (istream& is, string& str);
Get line from stream into string
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, ‘\n‘, for (2)).
The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.
Each extracted character is appended to the string as if its member push_back was called.

遇见delim就停止,并discard,下次extract从delim后开始


2.返回值

返回一个istream的引用,可隐式转换为bool型,所以可在while(),if()中使用。当ss被extract完后,ss值还是为true,但如果再次调用getline()去取,ss将为false。



【LeetCode笔记】Compare Version Numbers

标签:c++   stringstream   getline   leetcode   

原文地址:http://blog.csdn.net/uncle_cat/article/details/44149149

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!