2017.10.21 LeetCode

来源:互联网 发布:女网球运动服知乎 编辑:程序博客网 时间:2024/06/03 20:08

28. Implement strStr()

Description

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

题意: 让你实现在c语言中的strstr函数,给你两个字符串string  haystack,string  needle,其中问你needle 是否在haystack里面出现过,出现过的话返回出现的位置,没出现过的话返回-1

分析: 我们可以暴力的做,但是太复杂了,可以利用string::find函数,来实现如果找到话返回位置,找不到的话返回 该字符串的npos值

参考函数

class Solution {public:    int strStr(string haystack, string needle) {        int p = haystack.find(needle);        if(p == haystack.npos){            return -1;        }         return p;    }};

13. Roman to Integer

Description

Given a roman numeral, convert it to an integer.

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

附:
这里写图片描述

这里写图片描述

题意: 就是给你一个罗马的数字,让你转化成阿拉伯数字

分析: 一开始想直接枚举一个一个的来,发现太复杂啦,借鉴了下别人的思路,直接按位把它转化成数字,然后在利用string::find()函数,有没有”IV”,”IX”……等等子串,如果存在的话再减去相应的值,因为这些都是不符合相加的,比如 “IV” 吧,一开始按位相加的话ans = 1+5 = 6,我们发现只要出现了”IV”这个子串,就多加了2,所以要在减去2

参考函数

class Solution {public:    int romanToInt(string s) {        int ans = 0;        for(int i = 0;i < s.size();i++) {            if(s[i] == 'I') ans += 1;            if(s[i] == 'V') ans += 5;            if(s[i] == 'X') ans += 10;            if(s[i] == 'L') ans += 50;            if(s[i] == 'C') ans += 100;            if(s[i] == 'D') ans += 500;            if(s[i] == 'M') ans += 1000;        }        if(s.find("IV") != s.npos) ans -= 2;        if(s.find("IX") != s.npos) ans -= 2;        if(s.find("XL") != s.npos) ans -= 20;        if(s.find("XC") != s.npos) ans -= 20;        if(s.find("CD") != s.npos) ans -= 200;        if(s.find("CM") != s.npos) ans -= 200;        return ans;    }};
原创粉丝点击