[Leetcode] 13, 38, 58

来源:互联网 发布:手机淘宝自动秒杀软件 编辑:程序博客网 时间:2024/05/17 09:23

13. Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Solution: 罗马数字转十进制数的规则如下:

摘自:http://www.cnblogs.com/rustfisher/p/4830704.html

首先要来了解一下罗马数字表示法,基本字符有7个:I,V,X,L,C,D,M,分别表示1,5,10,50,100,500,1000。

在构成数字的时候,有下列规则:

1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;

2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;

3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;

4、正常使用时,连写的数字重复不得超过三次。

Code:

class Solution {public:    int romanToInt(string s) {        map<char, int> m;        m['I'] = 1;        m['V'] = 5;        m['X'] = 10;        m['L'] = 50;        m['C'] = 100;        m['D'] = 500;        m['M'] = 1000;                int tmpt = 0;        int sum = 0;        for(int i=s.size()-1; i>=0; i--){            cout<<m[s[i]]<<" ";            if(m[s[i]]<tmpt)                sum -= m[s[i]];            else                sum += m[s[i]];            tmpt = m[s[i]];        }        return sum;    }};


38. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     12.     113.     214.     12115.     111221

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1Output: "1"

Example 2:

Input: 4Output: "1211"

Solution: 理解题意之后模拟过程。

Code:

class Solution {public:    string countAndSay(int n) {        string s = "1";        for(int i=1; i<n; i++){            s = nextString(s);        }        return s;    }private:    string nextString(string s){        string ans = "";        for(int i=0; i<s.size(); ){            int tmp = i+1;            while(tmp<s.size()){                if(s[tmp]==s[i]) tmp++;                else break;            }            ans.push_back(tmp-i+'0');            ans.push_back(s[i]);            i = tmp;        }        return ans;    }};


58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example, 
Given s = "Hello World",
return 5.

Solution: 细节实现题。

Code:

class Solution {public:    int lengthOfLastWord(string s) {        int l=0;        int start = s.size()-1;        for(int i=s.size()-1; i>=0; i--){            if(s[i]!=' '){                start = i;                break;            }        }        cout<<start<<endl;        for(int i=start; i>=0; i--){            if(s[i]!=' ') l++;            else break;        }        return l;    }};


原创粉丝点击