leetcode 字符串类型题
1,Vaild Palindrome
bool isPalindrome(string& s) {
transform(s.begin(), s.end(), s.begin(), tolower); // 把字符全部转换成小写
int left = ;
int right = s.length()-;
while (left < right) {
if (!isalnum(s[left])) ++left;
else if (!isalnum(s[right])) --right;
else if (s[left] != s[right]) return false;
else {
++left;
--right;
}
}
return true;
}
isPalindrome
2,Implement strStr
int strStr(const string& haystack, const string& needle) { // KMP 算法,BM 算法
if (needle.empty()) return ;
const int N = haystack.length() - needle.length();
for (int i = ; i <= N; ++i) {
int j = i; // 源串索引
int k = ; // 字串索引
while (haystack[j] == needle[k] && j < haystack.length() && k < needle.length()) {
++j;
++k;
}
if (k == needle.length()) return i;
}
return -;
}
strStr
3,String to Integer(atoi)
int myAtoi(const string& str) {
const int n = str.length();
int sign = ;
int i = ;
int num = ; while (str[i] == ' ' && i < n) ++i; // 前面的字符处理
if (str[i] == '+') {
sign = ;
++i;
}
else if (str[i] == '-') {
sign = -;
++i;
}
for (; i < n; ++i) {
if (str[i] < '' || str[i] > '')
break;
num = num * + str[i] - ''; if (sign == && num > INT_MAX)
return INT_MAX;
else if (sign == - && num > INT_MIN + )
return INT_MIN;
}
return sign * num;
}
myAtoi
4,Add Binary
string addBinary(string a, string b) { // 思路同 Add Binary(链表类型题) plusOne(数组类型题)
string result;
int carry = ;
reverse(a.begin(), a.end()); // 先反转两个数组,从低位开始相加
reverse(b.begin(), b.end());
const int n = a.length() > b.length() ? a.length() : b.length();
for (int i = ; i < n; ++i) {
const int ai = i < a.length() ? a[i]-'' : ;
const int bi = i < b.length() ? b[i]-'' : ;
int value = (ai + bi + carry) % ;
carry = (ai + bi + carry) / ;
result.insert(result.begin(), value + '');
}
if (carry == )
result.insert(result.begin(), '');
return result;
}
addBinary
5,Longest Palindromic Substring(未实现)
6,Regular Expression Matching
bool isMatchI(const char *s, const char *p) { //递归版 有挑战的一道题目
if (*p == '\0') return *s == '\0'; //next char is not '*',then match current character
if (*(p + ) != '*') {
if (*p == *s || (*p == '.' && *s != '\0')) { // correctly match
return isMatchI(s + , p + );
}
else { // failed match
return false;
}
}
else { // next char is '*'
while (*p == *s || (*p == '.' && *s != '\0')) {
if (isMatchI(s, p + )) {
return true;
}
s++;
}
return isMatchI(s, p + );
}
}
isMatch
7,Wildcard Matching
bool isMatchII1(const char *s, const char *p) { // 递归版
if (*p == '*') {
while (*p == '*') ++p; // skip continuous '*'
if (*p == '\0') return true;
while (*s != '\0' && !isMatchII1(s, p)) ++s; return *s != '\0';
}
else if (*p == '\0' || *s == '\0')
return *p == *s;
else if (*p == *s || *p == '?')
return isMatchII1(++s, ++p);
else
return false;
}
bool isMatchII2(const char *s, const char *p) { // 迭代版
bool star = false;
const char *str = s; // str 可以变,*str 不能变
const char *ptr = p; while (*str != '\0') {
switch (*ptr) {
case '?':
str++;
ptr++;
break;
case '*':
star = true;
while (*ptr == '*') ++p;
if (*ptr == '\0') return true;
break;
default:
if (*str != *ptr) {
if (!star)
return false;
str++;
}
}
}
while (*ptr == '*') ++ptr;
return (*ptr == '\0'); }
isMatch
8,Longest Common Prefix
string longestCommonPrefix1(vector<string>& strs) { // 纵向扫描
if (strs.empty()) return ""; for (int index = ; index < strs[].size(); ++index) { // 选取第一个字符串和其它字符串进行比较
for (int i = ; i < strs.size(); ++i) {
if (strs[i][index] != strs[][index])
return strs[].substr(, index);
}
}
return strs[];
} string longestCommonPrefix2(vector<string>& strs) { // 横向扫描
if (strs.empty()) return ""; int right_most = strs[].size() - ;
for (size_t i = ; i < strs.size(); ++i) {
for (int j = ; j <= right_most; ++j) {
if (strs[i][j] != strs[][j])
right_most = j - ;
}
}
return strs[].substr(, right_most + );
}
longestCommonPrefix
9,Valid Number
bool isNumber(const char *s) { //
char* endptr;
strtod(s, &endptr); if (endptr == s)
return false; for (; *endptr; ++endptr) {
if (!isspace(*endptr))
return false;
}
return true;
}
isNumber
10,Integet to Roman
string intToRoman1(int num) {
const int radix[] = { , , , , , , , , , , , , };
const string symbol[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; string roman;
for (size_t i = ; num > ; ++i) {
int count = num / radix[i];
num %= radix[i];
for (; count > ; --count)
roman += symbol[i];
}
return roman;
} string intToRoman2(int num) {
string res = "";
vector<int> val = { , , , , , , , , , , , , };
vector<string> str = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
for (int i = ; i < val.size(); ++i) {
while (num >= val[i]) {
num -= val[i];
res += str[i];
}
}
return res;
}
intToRoman
11,Roman to Integer
int romanToInt(const string& s) {
int result = ;
unordered_map<char, int> mapping;
mapping['I'] = ;
mapping['V'] = ;
mapping['X'] = ;
mapping['L'] = ;
mapping['C'] = ;
mapping['D'] = ;
mapping['M'] = ; for (size_t i = ; i < s.size(); i++) {
if (i > && (mapping[i] > mapping[i - ])) {
result += (mapping[s[i]] - * mapping[s[i - ]]);
}
else {
result += mapping[s[i]];
}
}
return result;
}
romanToInt
12,Count and Say
string getNext(const string& s) {
stringstream ss;
for (auto i = s.begin(); i != s.end();) {
auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i)); // 需要看看函数怎么用
ss << distance(i, j) << *i;
i = j;
}
return ss.str();
} string countAndSay(int n) {
string s("");
while (--n) {
s = getNext(s);
}
return s;
}
countAndSay
13,Anagrams(回文构词法)
vector<string> anagrams(vector<string>& strs) {
unordered_map<string, vector<string>> group;
for ( auto s = strs.begin(); s != strs.end();++s) {
string key = *s;
sort(key.begin(), key.end()); // 会修改原数据
group[key].push_back(*s);
}
vector<string> result;
for (auto it = group.cbegin(); it != group.cend(); ++it) {
if (it->second.size() > )
result.insert(result.end(), it->second.begin(), it->second.end());
}
return result;
}
anagrams
14,Simplify Path
string simplifyPath(const string& path) {
string dir;
stack<string> stk;
string result; for (auto i = path.begin(); i != path.end();) {
++i;
auto j = find(i, path.end(), '/');
dir = string(i, j); /* 获取两个 / / 之间的内容 */ if (!dir.empty() && dir !="/" && dir != ".") {
if (dir == "..") {
if (!stk.empty())
stk.pop();
}
else
stk.push(dir);
}
i = j;
}
//stringstream out; // 可以用字符串流保存,然后通过 out.str() 转化成字符串返回
if (stk.empty())
//out << "/";
result = "/";
else {
while (!stk.empty()) {
string s = stk.top();
stk.pop();
//out << '/' << s;
result += "/" + s;
}
}
// return out.str();
return result;
}
simplifyPath
15,Length of Last Word
int lengthOfLastWord1(const string& s) { // STL::find_if,find_if_not,distance
auto first = find_if(s.rbegin(), s.rend(), isalpha);
auto last = find_if_not(first, s.rend(), isalpha);
return distance(first, last);
} int lengthOfLastWord2(const string& s) {
int len = ;
for (int i = ; i < s.length(); ++i) {
if (s[i] != ' ')
++len;
else
len = ;
}
return len;
}
lengthOfLastWord
c++常用函数
1, split
#include<vector>
#include<iostream>
#include<algorithm>
#include<cstring> using namespace std; vector<string> split(string str, const char* c) {
char *cstr, *p;
vector<string> res;
cstr = new char[str.length()+];
strcpy(cstr, str.c_str());
p = strtok(cstr, c); while(p != NULL) {
res.push_back(p);
p = strtok(NULL, c);
}
delete cstr; // 释放内存
return res;
} int main() {
string s = "a AND B";
const char *c = " ";
vector<string> ans;
ans = split(s, c); for(int i=;i<ans.size();i++) {
cout << ans[i] << endl;
}
return ;
}
split
以上题目来源于:http://www.github.com/soulmachine/leetcode
leetcode 字符串类型题的更多相关文章
- leetcode 链表类型题总结
链表测试框架示例: // leetcodeList.cpp : 定义控制台应用程序的入口点.vs2013 测试通过 // #include "stdafx.h" #include ...
- leetcode 动态规划类型题
1,Triangle int mininumTotal(vector<vector<int>>& triangle) { ; i >= ; --i) { ; j ...
- leetcode 树类型题
树的测试框架: // leetcodeTree.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <iostream& ...
- leetcode 数组类型题总结
1,removeDuplicates(I) int removeDuplicatesI(vector<int>& nums){ // 重新组织数组,同 removeDuplicat ...
- leetcode 数组类型题
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <Windows.h& ...
- 【python】Leetcode每日一题-扰乱字符串
[python]Leetcode每日一题-扰乱字符串 [题目描述] 使用下面描述的算法可以扰乱字符串 s 得到字符串 t : 如果字符串的长度为 1 ,算法停止 如果字符串的长度 > 1 ,执行 ...
- LeetCode 第 3 题(Longest Substring Without Repeating Characters)
LeetCode 第 3 题(Longest Substring Without Repeating Characters) Given a string, find the length of th ...
- 【leetcode 字符串处理】Compare Version Numbers
[leetcode 字符串处理]Compare Version Numbers @author:wepon @blog:http://blog.csdn.net/u012162613 1.题目 Com ...
- leetcode 第188题,我的解法,Best Time to Buy and Sell Stock IV
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255) ...
随机推荐
- Tomcat 之session 持久化1
Tomcat 之session 持久化原理 几个概念: Manager 接口,其实就是指的是对 其Sesison 的管理, 其默认实现是StandardManager (内部没有任何Store对象实 ...
- spark基础知识介绍(包含foreachPartition写入mysql)
数据本地性 数据计算尽可能在数据所在的节点上运行,这样可以减少数据在网络上的传输,毕竟移动计算比移动数据代价小很多.进一步看,数据如果在运行节点的内存中,就能够进一步减少磁盘的I/O的传输.在spar ...
- django之ModelBase类及mezzanine的page link类
class ModelBase(type): """ Metaclass for all models. """ def __new__(c ...
- 深度学习原理与框架-卷积网络细节-图像分类与图像位置回归任务 1.模型加载 2.串接新的全连接层 3.使用SGD梯度对参数更新 4.模型结果测试 5.各个模型效果对比
对于图像的目标检测任务:通常分为目标的类别检测和目标的位置检测 目标的类别检测使用的指标:准确率, 预测的结果是类别值,即cat 目标的位置检测使用的指标:欧式距离,预测的结果是(x, y, w, h ...
- C++中几种测试程序运行时间的方法<转>
转的地址:https://www.cnblogs.com/silentteen/p/7532855.html 1.GetTickCount()函数 原理: GetTickCount()是获取系统启动后 ...
- ABAP-权限查询-用户信息系统
事务代码:SUIM
- SourceTree commit information window消失解决办法
https://answers.atlassian.com/questions/15282793/sourcetree-how-to-show-commit-information-panel 执行命 ...
- java 实现Bridge模式(转)
原文:http://chjking.blog.163.com/blog/static/6439511120081152534252/ 看了网上一些关于咖啡加奶的例子,觉得真是天下文章一大抄,不管好的坏 ...
- RH_KABI_RESERVE的使用
struct mm_struct { .......... #if defined(__GENKSYMS__) || !defined(CONFIG_SPAPR_TCE_IOMMU) /* We're ...
- byte类型的127+1=-128?
public class Test2 { public void add(Byte b) { b = b++; } public void test() { Byte a = 127; Byte ...