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::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; }};
阅读全文
0 0
- 2017.10.21 LeetCode
- Leetcode 21
- LeetCode #21
- 2017.10.22 LeetCode
- 2017.10.23 LeetCode
- 2017.10.25 LeetCode
- 2017.10.27 LeetCode
- 2017.10.28 LeetCode
- 2017.10.29 LeetCode
- 2017.10.30 LeetCode
- 2017.10.31 LeetCode
- Leetcode【21】:Generate Praentheses
- LeetCode 21 Palindrome Partitioning
- LeetCode 21 Generate Parentheses
- <LeetCode><Easy> 21 MergeTwoSortedLists
- Leetcode no. 21
- leetcode #21 in cpp
- leetCode练习(21)
- jqeruy时间处理
- Java设计模式知识-笔记六
- C++风格_作用域
- nginx服务器的搭建
- 【STM32】创建一个新工程
- 2017.10.21 LeetCode
- centos(2)-VMware Workstation Player安装centos7
- 安装部署nvm、npm、nodejs之前先了解清楚三者之间关系
- 如何选择正确的控制系统?PLC和DCS各有不同
- 欢迎使用CSDN-markdown编辑器
- Machine Learning学习之岭回归
- path类,流和文件流
- Map集合
- [Oracle 11g r2(11.2.0.4.0)]案例分析7-丢失本地心跳导致的集群重新配置