• Compare Version Numbers


    1、题目描述

    2、解法分析

    首先,使用 ' . ' 号分隔的version 每两个点号之间的数字就是数值,使用 vector<string> 将每个version 字符串中的字符串摘取出来,然后对比对应的字符串表示的数字大小,本题使用 C++ 标准库中 stoi() 函数,将string 转换为数字。

    3、代码

     1 int compareVersion(string version1, string version2) {
     2        
     3         vector<string> v1;
     4         vector<string> v2;
     5         string::iterator it1 = version1.begin();
     6         
     7         string s1 ;
     8         while( it1 != version1.end() ){
     9             if( *it1 == '.') {
    10                 v1.push_back(s1);
    11                 s1.clear() ;
    12             } else{
    13                 s1 += *it1;
    14             }
    15             it1++;
    16         }
    17         v1.push_back( s1 ) ;
    18         
    19         string s2;
    20         auto it2 = version2.begin() ;
    21         while( it2 != version2.end() ){
    22             if( *it2 == '.' ){
    23                 v2.push_back(s2);
    24                 s2.clear();
    25             }else{
    26                 s2 += *it2;
    27             } 
    28             it2++;
    29         }
    30         v2.push_back( s2 );
    31         
    32         vector<string>::iterator p1 = v1.begin() ;
    33         vector<string>::iterator p2 = v2.begin() ;
    34         while( p1 != v1.end() && p2 != v2.end() ){
    35             if( stoi( *p1) > stoi(*p2)  ){
    36                 return 1;
    37             }else if( stoi(*p1) < stoi(*p2) ){
    38                 return -1;
    39             }
    40             ++p1;
    41             ++p2;
    42         }
    43         
    44         while( p1 != v1.end() )
    45         {
    46             if( stoi(*p1) > 0 )
    47                 return 1;
    48             p1++;
    49         }
    50             
    51         while( p2 != v2.end() )
    52         {
    53             if( stoi(*p2) > 0 )
    54                 return -1;
    55             p2++;
    56         }
    57         
    58         return 0;
    59   
    60     }
    pp
  • 相关阅读:
    [Leetcode] Distinct Subsequences
    [Leetcode] Restore IP Addresses
    [Leetcode] Substring with Concatenation of All Words
    [Leetcode] Palindrome Partitioning II
    [Leetcode] Palindrome Partitioning
    [Leetcode] Maximal Rectangle
    [Jobdu] 题目1493:公约数
    [Leetcode] Merge k Sorted Lists
    [Leetcode] Gray Code
    opencv2-新特性及Mat
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/9295257.html
Copyright © 2020-2023  润新知