leetcode One type of Roman numerals and interchangeable numbers

      I do not know what big brother said: questions about strings can be solved with a pointer or hash.

      Roman numerals to Digital:

      We thought: we can observe the law: Under normal circumstances, represents the first large letters, small letters at the post;

                  In special cases, small letters large letters will be before, but the corresponding obtained value is large alphabet - minuscule

         So, we can use mapping hash table size, use a hash table to compare the Roman alphabet, in general, direct + the corresponding value, otherwise - the corresponding values

class Solution {
 public :
     // a hash table mapping characters, special process conditions: before the letters <letter after letter becomes negative before == 
    int romanToInt ( String S) { 
        Map < char , int > the hash; 
        the hash [ ' the I ' ] = . 1 ; 
        the hash [ ' V ' ] = . 5 ; 
        the hash [ ' X- ' ] = 10 ; 
        the hash [ ' L ' ] = 50 ; 
        the hash [ ' C'] = 100;
        hash['D'] = 500;
        hash['M'] = 1000;
        
        int sum = 0;
        for(int i = 0;i<s.size();++i)
        {
            if(hash[s[i]] < hash[s[i+1]])
            {
                sum-=hash[s[i]];
                continue;
            }
            sum+=hash[s[i]];
        }
        
        return sum;
    }
};

      Digital transfer Roman numerals:

      I thought: This question is crucial with the greedy algorithm, try using fewer letters to represent the largest number, and then to observe the law, from largest to smallest Rome find those necessary number (the number of Roma in Rome can not be obtained by adding the number of the previous)

      So, let's build the necessary number of tables in Rome, and then to calculate greedy thoughts.

class Solution {
 public :
     // greedy algorithm: using the minimum character, beginning from the largest 
    String intToRoman ( int NUM) { 
        Map < int , String > = {{mapRom . 1 , " the I " }, { . 4 , " IV " }, { . 5 , " V " }, { . 9 , " IX " },      
                                                { 10 , " X- " }, { 40 ,"XL"},{50,"L"}, {90,"XC"},
                                                {100,"C"},{400,"CD"},{500,"D"},    
                                                {900,"CM"}, {1000,"M"} };=
        self r_iter mapRom.rbegin();
        
        string ret;
       
        while(num>0 && r_iter!=mapRom.rend())
        {
            if(num >= r_iter->first)
            {
                ret += r_iter->second;
                num-= r_iter->first;
            }
            else
                r_iter++;
        }
        return ret;

        
    }
};        

 

Guess you like

Origin www.cnblogs.com/Duikerdd/p/11752770.html