一些leetcode算法题
DFS算法
思想:一直往深处走,直到找到解或者走不下去为止
DFS(dep,...) // dep代表目前DFS的深度
{
if (找到解或者走不下去了){
return;
}
枚举下种情况,DFS(dep + , ...)
} DFS: 使用栈保存未被检测的节点,结点按照深度优先的次序被访问并依次压入栈中,并以相反的次序出栈进行新的检测
类似于树的先根遍历,深搜的例子:走迷宫,没有办法用分身术来站在每一个走过的位置。
例子:
leetcode class Solution {
public:
string DFS(string s, int &k){ // 在所有的层中是维护一个共同的索引值k
string ans;
int cnt = ;
while(k < s.size())
{
if(isdigit(s[k])){ // 判断是否是数字
cnt = cnt * + s[k++]-''; // 如果是遇到100这样的数字,那么则需要这样处理
}
else if(s[k]=='['){ // 如果是左括号,则要进入下层递归
string tem = DFS(s, ++k); // 递归调用
for(int i = ; i < cnt; i++){
ans += tem;
}
cnt = ; //
}
else if(s[k]==']'){
k++;
return ans;
}
else ans += s[k++]; // 若是普通数字就直接加上
}
return ans;
} string decodeString(string s){
string res;
int k = ;
return DFS(s, k);
}
}; leetcode Unique Substring in Wraparounding string 思路:这道题说有一个无限长的封装字符串,然后又给了我们另一
个字符串p,问我们p有多少非空子字符串在封装字符串中。我们通过
观察题目中的例子可以发现,由于封装字符串是26个字符按顺序无限
循环组成的,那么满足题意的p的子字符串要么是单一的字符,要么是
按字母顺序的子字符串。这道题遍历p的所有子字符串会TLE,因为如
果p很大的话,子字符串很多,会有大量的满足题意的重复子字符串,
必须要用到trick,而所谓技巧就是一般来说你想不到的方法。我们看
abcd这个字符串,以d结尾的子字符串有abcd, bcd, cd, d,那么我们
可以发现bcd或者cd这些以d结尾的字符串的子字符串都包含在abcd中,
那么我们知道以某个字符结束的最大字符串包含其他以该字符结束的字符
串的所有子字符串,说起来很拗口,但是理解了我上面举的例子就行。
那么题目就可以转换为分别求出以每个字符(a-z)为结束字符的最长连续
字符串就行了,我们用一个数组cnt记录下来,最后再求出数组cnt的所有
数字之和就是我们要的结果啦 class Solution {
public:
int findSubstringInWraproundString(string p) { // 很有技巧的一个题
vector<int> cnt(, ); // 对应26个字母,注意vector的初始化
int len = ;
for (int i = ; i < p.size(); ++i) {
if (i > && (p[i] == p[i - ] + || p[i - ] - p[i] == )) {
++len;
}
else {
len = ; // 若是不再连续就将len置1重新开始
}
cnt[p[i] - 'a'] = max(cnt[p[i] - 'a'], len); // 用len的值更新cnt的值
}
return accumulate(cnt.begin(), cnt.end(), ); // 将cnt的所有的值累加起来
}
}; leetcode . Palindromic Substrings 回文字串 题目:
Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist
of same characters. Example :
Input: "abc"
Output:
Explanation: Three palindromic strings: "a", "b", "c".
Example :
Input: "aaa"
Output:
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". 思路一:dp思想
参考链接:http://blog.csdn.net/lishichengyan/article/details/77103324
定义d[i][j]:若从i到j的字符串为回文,则为真(),否则为假(),那么d[i][j]为真的前提是:头尾两个字符串相同并且去掉头尾以后的字串也是
回文(即d[i+][j-]为真),这里面要注意特殊情况,即:去掉头尾以后为空串,所以如果j-i<,并且头尾相等,也是回文的。 class Solution {
public:
int countSubstrings(string s) {
int n = s.size(), count = ;
vector<vector<int>> dp(n, vector<int> (n)); //二维vector初始化,打表
for ( int end = ; end < n; ++end ) {
dp[end][end] = ; // 每一个字符都是一个回文
++count;
for ( int start = ; start < end; ++start ) {
if ( s[start] == s[end] && (start+ >= end- || dp[start+][end-])) {
dp[start][end] = ;
++count; // 有一个为真那么结果值就加一
}
}
}
return count;
}
}; 题意是给你一个字符串,求它有多少个回文子串。注意回文子字符串有奇数和偶数两种形式,,奇数
以字符串每一个字符为回文中心,然后向两边扩散,求以每个中心获得的回文子串个数,然后加起来。
. 偶数。把每个i位置作为最中间两个字符的左边那个,即i,i+1两个数是回文中心。把奇数和偶数的情况加起来就是
结果
思路二: 使用从 中心向外扩展的方法,注意回文的字符串个数为奇数或者偶数的时候 class Solution {
public:
int helper(string s, int start, int end){
int res = ;
int len = s.size();
while (start >= && end <= len && s[start] == s[end]){
res++;
start--;
end++;
}
return res;
}
int countSubstrings(string s) {
int len = s.size(), cnt = ;
for (int i = ; i < len; i++){
cnt += helper(s, i, i); // 回文为奇数的时候
cnt += helper(s, i, i + ); // 回文为偶数的时候
}
return cnt;
}
}; Leetcode . Baseball Game You're now a baseball game point recorder. Given a list of strings, each string can be one of the following types: Integer (one round's score): Directly represents the number of points you get in this round.
"+" (one round's score): Represents that the points you get in this round are the sum of the last two valid round's points.
"D" (one round's score): Represents that the points you get in this round are the doubled data of the last valid round's points.
"C" (an operation, which isn't a round's score): Represents the last valid round's points you get were invalid and should be removed.
Each round's operation is permanent and could have an impact on the round before and the round after. You need to return the sum of the points you could get in all the rounds. Example :
Input: ["","","C","D","+"]
Output:
Explanation:
Round : You could get points. The sum is: .
Round : You could get points. The sum is: .
Operation : The round 's data was invalid. The sum is: 5.
Round : You could get points (the round 's data has been removed). The sum is: 15.
Round : You could get + = points. The sum is: . Example :
Input: ["","-2","","C","D","","+","+"]
Output:
Explanation:
Round : You could get points. The sum is: .
Round : You could get - points. The sum is: .
Round : You could get points. The sum is: .
Operation : The round 's data is invalid. The sum is: 3.
Round : You could get - points (the round 's data has been removed). The sum is: -1.
Round : You could get points. The sum is: .
Round : You could get - + = points. The sum is .
Round : You could get + = points. The sum is . Solution: class Solution {
public:
int calPoints(vector<string>& ops) {
int res = ;
int len = ops.size();
vector<int> data;
for (int i = ; i < len; i++){
if (ops[i] == "C"){
int tmp1 = data.back();
data.pop_back();
res -= tmp1;
}else if(ops[i] == "D"){
int tmp0 = * data.back();
data.push_back(tmp0);
res += tmp0;
}else if (ops[i] == "+"){
int tmp2 = data.back();
int tmp3 = data[data.size() - ];
data.push_back(tmp2 + tmp3);
res += (tmp2 + tmp3);
}else{
int tmp = stoi(ops[i]);
data.push_back(tmp);
res += tmp;
} }
return res;
}
}; leetcode . Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is . Given "bbbbb", the answer is "b", with the length of . Given "pwwkew", the answer is "wke", with the length of . Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 最笨的方法:o(n^):
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = , maxtmp;
set<char> substr;
int len = s.size();
if (len == ){
res = ;
return res;
}
for (int i = ; i < len; i++){
substr.insert(s[i]);
maxtmp = ;
for (int j = i + ; j < len; j++){
if (substr.find(s[j]) != substr.end()){
break;
}
else{
substr.insert(s[j]);
maxtmp++;
}
}
substr.clear();
res = max(res, maxtmp);
}
return res;
}
}; Leetcode . Binary Tree Paths Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: / \ \ All root-to-leaf paths are: ["1->2->5", "1->3"] /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void helper(TreeNode* root, string path, vector<string> &result){
if (!root->left && !root -> right){ // 注意这里判断的条件是叶子节点的时候
result.push_back(path);
return;
} if (root -> left){
helper(root -> left, path + "->" + to_string(root->left->val), result);
}
if (root -> right){
helper(root -> right, path + "->" + to_string(root->right->val), result);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if (!root){
return result;
}
helper(root, to_string(root->val), result);
return result;
}
};
一些leetcode算法题的更多相关文章
- LeetCode算法题-Subdomain Visit Count(Java实现)
这是悦乐书的第320次更新,第341篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第189题(顺位题号是811).像"discuss.leetcode.com& ...
- LeetCode算法题-Number of Lines To Write String(Java实现)
这是悦乐书的第319次更新,第340篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第188题(顺位题号是806).我们要将给定字符串S的字母从左到右写成行.每行最大宽度为 ...
- LeetCode算法题-Unique Morse Code Words(Java实现)
这是悦乐书的第318次更新,第339篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第186题(顺位题号是804).国际莫尔斯电码定义了一种标准编码,其中每个字母映射到一系 ...
- LeetCode算法题-Rotate String(Java实现)
这是悦乐书的第317次更新,第338篇原创 在开始今天的算法题前,说几句,今天是世界读书日,推荐两本书给大家,<终身成长>和<禅与摩托车维修艺术>,值得好好阅读和反复阅读. 0 ...
- LeetCode算法题-Rotated Digits(Java实现)
这是悦乐书的第316次更新,第337篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第185题(顺位题号是788).如果一个数字经过180度旋转后,变成了一个与原数字不同的 ...
- LeetCode算法题-Letter Case Permutation(Java实现)
这是悦乐书的第315次更新,第336篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第184题(顺位题号是784).给定一个字符串S,将每个字母单独转换为小写或大写以创建另 ...
- LeetCode算法题-Minimum Distance Between BST Nodes(Java实现-四种解法)
这是悦乐书的第314次更新,第335篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第183题(顺位题号是783).给定具有根节点值的二叉搜索树(BST),返回树中任何两个 ...
- LeetCode算法题-Jewels and Stones(Java实现)
这是悦乐书的第313次更新,第334篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第182题(顺位题号是771).字符串J代表珠宝,S代表你拥有的石头.S中的每个字符都是 ...
- LeetCode算法题-Toeplitz Matrix(Java实现)
这是悦乐书的第312次更新,第333篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第181题(顺位题号是766).如果从左上角到右下角的每个对角线具有相同的元素,则矩阵是 ...
- LeetCode算法题-Prime Number of Set Bits in Binary Representation(Java实现)
这是悦乐书的第311次更新,第332篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第180题(顺位题号是762).给定两个正整数L和R,在[L,R]范围内,计算每个整数的 ...
随机推荐
- JavaScript实现元素拖动性能优化
前言:前几天没事干写了个小网站,打算用原生的javascript实现元素的拖动,但是事情并没有想象的那么顺利,首先是实现了拖动的元素卡的不能再卡,简直不能够,上图~~ 看见没?这就是效果,简直让人欲哭 ...
- Win10 C盘桌面文件右上方的两个蓝色箭头解决方案
之前看网上有很多桌面蓝色箭头的解决方案,也进行了一些尝试 可是每次Win10系统更新之后蓝色箭头就会重新显示. 最终方案:将建立在桌面的C盘文件移到D盘,桌面创建对应的快捷方式. 一劳永逸,暴力破解.
- PAT乙级题:1003我要通过!
#include <iostream> #include <string> #include <vector> #include <algorithm> ...
- Python 列表&元组&字典&集合
列表(list) 有序性,可存储任意类型的值 通过偏移存取,支持索引来读取元素,第一个索引为0 ,倒数第一个索引为-1 可变性 ,支持切片.合并.删除等操作 可通过索引来向指定位置插入元素 可通过po ...
- JDK动态代理和cglib代理详解
JDK动态代理 先做一下简单的描述,通过代理之后返回的对象已并非原类所new出来的对象,而是代理对象.JDK的动态代理是基于接口的,也就是说,被代理类必须实现一个或多个接口.主要原因是JDK的代理原理 ...
- C#事件の事件解析
事件(event)是基于windows消息处理机制的类,封装的更好,让开发者无须知道底层的消息处理机制,就可以开发出强大的基于事件的应用程序来.委托(delegate)委托可以理解成为函数指针,不同的 ...
- 浅析 PHP 中的 Generator
浅析 PHP 中的 Generator Miss Wang php开发案例 前天 何为 Generator 从 PHP 5.5 开始,PHP 加入了一个新的特性,那就是 Generator,中文译为生 ...
- 在 PHP 7 中不要做的 10 件事
在 PHP 7 中不要做的 10 件事 1. 不要使用 mysql_ 函数 这一天终于来了,从此你不仅仅“不应该”使用mysql_函数.PHP 7 已经把它们从核心中全部移除了,也就是说你需要迁移到好 ...
- Python中的Numpy入门教程
1.Numpy是什么 很简单,Numpy是Python的一个科学计算的库,提供了矩阵运算的功能,其一般与Scipy.matplotlib一起使用.其实,list已经提供了类似于矩阵的表示形式,不过nu ...
- day1 计算机组成、操作系统
一:编程与编程的目的 1.什么是语言?什么是编程语言? 语言是一个事物与另一个事物沟通的介质. 编程语言是程序员与计算机沟通的介质. 2.什么是编程?为什么要编程? 编程是程序员将自己想要让计算机做的 ...