Count number of Palindrome Substring numbers.

工业互联网工控安全与工业质检AI大模型建设方案.pptx 立即下载
/*
  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;
}

2024 《计算机网络》实验教学指导书.doc 立即下载

相关推荐

Dev C++调试程序方法详解

Dev C++调试程序方法详解

weixin_70641798的博客 1万+

SPOJ Number of Palindromes(回文树)

SPOJ Number of Palindromes(回文树)

Dacc123的博客 1120

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

loveling丶的博客 3597

[编程之美]资格赛 B Palindrome

既然这个是资格赛,  时间也比较充裕, 我就讲解一下我做题的过程 Time Limit:2000ms Case Time Limit:1000ms Memory Limit:256MB Description Given a string, calculate the number of subsequences that are palindrome.

yihuihe 936

深入解析MTK平台hang_detect机制:从原理到实战调试

本文深入解析了MTK平台hang_detect机制的工作原理与实战调试技巧。作为系统健康监测的核心机制,hang_detect通过多层级监控体系检测应用层和内核层异常,结合Kernel_exception等日志信息快速定位问题。文章详细介绍了典型问题案例、调试方法及预防措施,帮助开发者提升MTK平台系统稳定性调试能力。

purple的博客 1004

使用libx265对YUV进行h265编码

使用libx265对YUV进行h265编码

Embedded engineer 3077

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

taoqick的专栏 1098

【计算机科学导论实验】加法图灵机模拟 题解

本文提供计算机科学导论课程“图灵机加法器”实验的个人思路,仅供参考。

Chavapa's blog 2576

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; /

ActiveCoder的博客 2079

4、分布式发电系统中用于改善电能质量的有源、无源和混合滤波器

本文探讨了分布式发电系统中,尤其是光伏(PV)系统运行过程中引入的电能质量问题,并分析了有源滤波器、无源滤波器及混合滤波器在改善电能质量方面的应用。文章详细介绍了光伏系统的建模、最大功率点跟踪(MPPT)技术,以及谐波、电压波动等技术问题,同时对各类滤波器的拓扑结构和控制方法进行了系统性总结。通过仿真实例比较了不同滤波器在减少谐波方面的效果,为实际工程应用提供了参考依据。

transformer2023的博客 89

OpenClaw零基础教程:30分钟搭建你的第一个AI自动化助手

别再看那些满是代码、专业术语的教程了,那些都是给程序员看的。这篇教程,我把所有步骤拆到了极致,你跟着点鼠标就行,点错了都没关系,大不了重装一遍,5分钟的事。

2601_94871597的博客 96

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

ActiveCoder的博客 954

基于锁相环的高精度频率分频器simulink建模与仿真

在现代电子系统中,高精度频率分频器扮演着至关重要的角色。它能够提供精确的频率参考,广泛应用于通信、仪器仪表、航空航天等领域。基于锁相环的高精度频率分频器具有结构简单、性能稳定等优点,成为了研究的热点。

平时工作较为繁忙,私信消息一般晚上回复,谢谢大家~~ 776

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

ActiveCoder的博客 728

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

ActiveCoder的博客 641

复分析 阿尔福斯(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

ActiveCoder的博客 623

深度学习工具包 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');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](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

ActiveCoder的博客 556

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

ActiveCoder的博客 517

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

ActiveCoder的博客 450

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

ActiveCoder的博客 448

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

ActiveCoder的博客 413

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

ActiveCoder的博客 408

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.

ActiveCoder的博客 395

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

ActiveCoder的博客 389

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

ActiveCoder的博客 384

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

ActiveCoder的博客 379
上一篇: Highest Frequency number in given intervals.
下一篇: Three Sum Variation.
ActiveCoder
博客等级 码龄11年 4粉丝 345原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值