/*
how many palindrome substring in a given string.
exp: "aba" return 4, "abba" return 6.
*/
#include <string>
#include <iostream>
using namespace std;
int palindromeSubs(string str) {
if(str.size() <= 1) return str.size();
int count = str.size();
for(int i = 1; i < str.size(); ++i) {
// even length subs
for(int l = i - 1, r = i; l >= 0 && r < str.size() && (str[l] == str[r]); l--, r++) {
count++;
}
// odd length subs
for(int l = i - 1, r = i + 1; l >= 0 && r < str.size() && (str[l] == str[r]); l--, r++)
count++;
}
return count;
}
int main(void) {
cout << palindromeSubs("aba") << endl;
cout << palindromeSubs("abba") << endl;
}
相关推荐
Dev C++调试程序方法详解
Dev C++调试程序方法详解
SPOJ Number of Palindromes(回文树)
SPOJ Number of Palindromes(回文树)
CNN经典论文(一)LeNet
Gradient-Based Learning Applied to Document Recognition(梯度学习在文档识别中的应用) Yann LeCun, Leon Bottou, Yoshua Bengio, and Patrick Haffner 发表时间:December 1998 期刊:Proceedings of the IEEE 影响:世界上第一个卷积神经网络 论文地址:Gradient-Based Learning Applied to Document Recognition
[编程之美]资格赛 B Palindrome
既然这个是资格赛, 时间也比较充裕, 我就讲解一下我做题的过程 Time Limit:2000ms Case Time Limit:1000ms Memory Limit:256MB Description Given a string, calculate the number of subsequences that are palindrome.
深入解析MTK平台hang_detect机制:从原理到实战调试
本文深入解析了MTK平台hang_detect机制的工作原理与实战调试技巧。作为系统健康监测的核心机制,hang_detect通过多层级监控体系检测应用层和内核层异常,结合Kernel_exception等日志信息快速定位问题。文章详细介绍了典型问题案例、调试方法及预防措施,帮助开发者提升MTK平台系统稳定性调试能力。
使用libx265对YUV进行h265编码
使用libx265对YUV进行h265编码
CareerCup Facebook Total number of substring palindrome Leetcode 647
Write a function for retrieving the total number of substring palindromes. For example the input is 'abba' then the possible palindromes= a, b, b, a, bb, abba So the result is 6. Updated at 11
【计算机科学导论实验】加法图灵机模拟 题解
本文提供计算机科学导论课程“图灵机加法器”实验的个人思路,仅供参考。
Add One
#include #include using namespace std; /* Given an integer, add its binary number by 1 without using '+'. */ int addOne(int number) { long long int a = number; if(a >= INT_MAX) return -1; /
4、分布式发电系统中用于改善电能质量的有源、无源和混合滤波器
本文探讨了分布式发电系统中,尤其是光伏(PV)系统运行过程中引入的电能质量问题,并分析了有源滤波器、无源滤波器及混合滤波器在改善电能质量方面的应用。文章详细介绍了光伏系统的建模、最大功率点跟踪(MPPT)技术,以及谐波、电压波动等技术问题,同时对各类滤波器的拓扑结构和控制方法进行了系统性总结。通过仿真实例比较了不同滤波器在减少谐波方面的效果,为实际工程应用提供了参考依据。
OpenClaw零基础教程:30分钟搭建你的第一个AI自动化助手
别再看那些满是代码、专业术语的教程了,那些都是给程序员看的。这篇教程,我把所有步骤拆到了极致,你跟着点鼠标就行,点错了都没关系,大不了重装一遍,5分钟的事。
LeetCode 91. Decode Ways
There are two ways to solve this problem. One is to solve it front-back, the other is back-front. I currently only wrote the back-front method: Suppose we have such a string: a0, a1, a2.... ai, a
基于锁相环的高精度频率分频器simulink建模与仿真
在现代电子系统中,高精度频率分频器扮演着至关重要的角色。它能够提供精确的频率参考,广泛应用于通信、仪器仪表、航空航天等领域。基于锁相环的高精度频率分频器具有结构简单、性能稳定等优点,成为了研究的热点。
Find the Thief (Facebook Interview)
Suppose there is a thief and n rooms. We can only any door to check whether the thief is there or not. during the night, the theif can either move left one room or right one room. Given a sequence of
SIMATIC S7-1200, S7-1500 PID 控制[手册]
SIMATIC S7-1200, S7-1500 PID 控制[手册]
Statistics and Machine Learning Toolbox
Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具
LeetCode 273. Integer to English Words
I changed the integer into string. If the length is not multiple of 3, append "0" ahead. Then, deal three digits by chunks. #include #include #include using namespace std; /* Convert a non-ne
复分析 阿尔福斯(Ahlfors) 第三版答案 英文
答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案
Subarray Sum to the given target value
Question: check if there is a subarray sum equals to the given target. This question should ask for clarifications. Whether the inputs are all positive, or it has negative numbers. 1: If all the num
深度学习工具包 DeepLearningToolbox
深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[](https://bitdeli.com/free "Bitdeli Badge")
Task Arrangement -- incomplete
Task schedule: Given a sequence of task like A B C, and a coldtime, which means you need to wait for that much time to start next[same] task. Now--- Input: string , n Output: the best task finishing
Facebook Phone Interview: Phone Number to Letter Combinations
Input: string of digits of arbitrary length output: print all possible letter combinations for those digits to screen. // This is a typical DFS algorithm. // Suppose we dont know the phone screen l
Facebook Phone Interview: 3, 4 Sum (Easy)
Facebook really usually has a high frequency of posting repetitive problems. This one is the typical 3Sum, 4Sum problem. Given an input array and a target value, find whether there are three/four
LeetCode 28. Implement strStr()
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. It is pretty hard to generalize KMP algorithm under stress and limited
LeetCode 76. Minimum Window Substring
#include #include #include #include using namespace std; /* Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). For
Maximum value's random index
#include #include #include #include #include using namespace std; // naive method // Go through the array once, find the max and the number of occurrences (n) // Generate a random number (r) bet
LeetCode. 314 Binary Tree Vertical Order Traversal
The basic idea to attach each node a col number. When goes to node->left. col -1, goes to right, col + 1. It will make things easier using a hashmap to store the nodes and correpsonding col number.
Three Sum Variation.
/* find three numbers that sums to 0, every number can be used repeatly. (Someone said it can be solved using hashMap?) Follow up: what if any K numbers. */ #include #include #include using nam
LeetCode 145. Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [3,2,1]. Stack Problem, One example
Remove Nested Comments.
Comments can be single line using //, or multiple line using /* */ We can use two flags to make the begin and end of two types of comments. string removeComments(string str) { string res; bool s
1万+



被折叠的 条评论
为什么被折叠?



