LeetCode214-20.8.29-最短回文串

【华为OD机试】字符串变换最小字符串(贪心策略-Java&Python&C++&JS实现) 【华为OD机试】字符串变换最小字符串(贪心策略-Java&Python&C++&JS实现) 给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较)。变换规则:交换字符串中任意两个不同位置的字符。 输入描述:一串小写字母组成的字符串s 输出描述:按照要求进行变换得到的最小字符串 补充说明:s是都是小写字符组成 阅读详情

链接:LeetCode214
过程:cv大法好
思路:看题解
代码:

class Solution {
    public String shortestPalindrome(String s) {
        int n = s.length();
        int[] fail = new int[n];
        Arrays.fill(fail, -1);
        for (int i = 1; i < n; ++i) {
            int j = fail[i - 1];
            while (j != -1 && s.charAt(j + 1) != s.charAt(i)) {
                j = fail[j];
            }
            if (s.charAt(j + 1) == s.charAt(i)) {
                fail[i] = j + 1;
            }
        }
        int best = -1;
        for (int i = n - 1; i >= 0; --i) {
            while (best != -1 && s.charAt(best + 1) != s.charAt(i)) {
                best = fail[best];
            }
            if (s.charAt(best + 1) == s.charAt(i)) {
                ++best;
            }
        }
        String add = (best == n - 1 ? "" : s.substring(best + 1));
        StringBuffer ans = new StringBuffer(add).reverse();
        ans.append(s);
        return ans.toString();
    }
}

2026华为OD机试(C语言)真题【E卷+A卷+B卷+C卷+D卷】目录+在线OJ 华为OD机试真题题库【E卷+A卷+B卷+C卷+D卷】目录,C语言实现。 阅读详情

相关推荐

2026华为OD机试(Python)真题【E卷+A卷+B卷+C卷+D卷】目录+在线OJ

华为OD机试真题题库【E卷+A卷+B卷+C卷+D卷】目录,Python实现。

MISAYAONE的博客 29万+

LeetCode: 214.最短回文串 &1312.让字符串成为回文串的最少插入次数

214.最短回文串 题目: 给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。 注意: 要求在字符串前面加入一个字符串,使得新字符串是回文,且长度是最短的。题目也可以改成从尾部加入 解法 其实目的就是在s中找到一个以头部字符为起点的最长回文串s1,然后s2(s中不是s1的部分)翻转贴到s的前面就完事了。但是复杂度是O(n**2), 有一种马拉车算法能到O(N)。 这里不介绍。 class Solution: def shortestPali

我的博客有点东西 1375

2026华为OD机试(JavaScript)真题【E卷+A卷+B卷+C卷+D卷】目录+在线OJ

华为OD机试真题题库【E卷+A卷+B卷+C卷+D卷】目录,JavaScript实现。

MISAYAONE的博客 8万+

腾讯 构造回文

给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢? 输出需要删除的字符个数。输入描述:输入数据有多组,每组包含一个字符串s,且保证:1<=s.length<=1000.输出描述:对于每组数据,输出一个整数,代表最少需要删除的字符个数。输入例子: abcda google输出例子: 2 2import java.util.Scanner;pub

不可不戒 2970

2026华为OD机试(JAVA&Go)真题【E卷+A卷+B卷+C卷+D卷】目录+在线OJ

华为OD机试真题题库【E卷+A卷+B卷+C卷+D卷】目录,Java实现。

MISAYAONE的博客 34万+

【华为OD机试真题 Python语言】32、字符串变换最小字符串 | 机试真题+思路参考+代码解析

给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较)。   变换规则:交换字符串中任意两个不同位置的字符

正在更新最新华为OD机试2025B卷,提供OJ在线刷题 344

Java 给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢? 输出需要删除的字符个数。

import java.io.BufferedInputStream; import java.util.Scanner; public class Main { private static Scanner cin; public static int Check(String s) { StringBuffer sb = new StringBuffer(); ...

jhp1266987的博客 3297

【100分】【字符串变换最小字符串】

在这个问题中,主要考察了对字符串操作的理解和实现能力。同时,还涉及到排序和字典序比较的概念,因为要找到最小字符并与其它字符进行交换以得到最小字符串。需要注意字符串边界情况以及代码的健壮性。给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较)。变换规则:交换字符串中任意两个不同位置的字符。abcdef已经是最小字符串,不需要交换。a和b进行位置交换,可以得到最小字符串。按照要求进行变换得到的最小字符串。一串小写字母组成的字符串s。【字符串变换最小字符串】

weixin_54707168的博客 1421

【华为OD题库-073】字符串变换最小字符串-java

题目描述:给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较)。变换规则:交换字符串中任意两个不同位置的字符。—串小写字母组成的字符串s按照要求进行变换得到的最小字符串s是都是小写字符组成abcdefabcdefabcdef已经是最小字符串,不需要交换bcdefaacdefba和b进行位置交换,可以得到最小字符串。

yangqin@1225的博客 1545

【华为OD机试真题JAVA】最小字符串问题

给定一个字符串S,最多只能进行一次变换,返回变化后能得到的最小字符串(字典序)交换字符串中任意两个不同位置的字符。按照要求变换得到最小字符串。一串小写字母组成的字符串。

风中追风 565

STM32G030C8T6 ADC+DMA实战:同时采集外部电压和芯片温度的完整代码流程

本文详细介绍了STM32G030C8T6芯片通过ADC+DMA实现外部电压和芯片内部温度采集的完整流程。从硬件设计到CubeMX配置,再到驱动模块化实现与系统优化,提供了高精度多通道采集系统的实战指南,特别适合嵌入式开发者在工业控制和环境监测项目中应用。

weixin_42653691的博客 467

leetcode **214. 最短回文串(2020.8.29)

【题目】**214. 最短回文串 给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。 示例 1: 输入: "aacecaaa" 输出: "aaacecaaa" 示例 2: 输入: "abcd" 输出: "dcbabcd" 【解题思路1】字符串哈希 class Solution { public String shortestPalindrome(String s) { int n = s.length();

Sophia_fez的博客 387

TRK-MPC5634M开发板实战:从硬件解析到CAN、ADC外设驱动调试

在嵌入式系统开发,尤其是汽车电子和工业控制领域,微控制器(MCU)是核心执行单元。其工作原理基于处理器内核、存储器和丰富的外设接口协同工作,通过软件编程实现对硬件的精确控制。这种技术价值在于能够为严苛环境提供可靠、实时的控制解决方案。典型的应用场景包括汽车车身控制、网关、电池管理系统以及工业自动化设备。本文聚焦于恩智浦(NXP)基于Power Architecture e200z0内核的汽车级MCU——MPC5634M,并以其官方评估板TRK-MPC5634M为平台,深入探讨其硬件设计逻辑、软件环境搭建及核

weixin_29997523的博客 288

Leetcode: NO.214 最短回文串 递归

题目 给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。 示例 1: 输入: "aacecaaa" 输出: "aaacecaaa" 示例 2: 输入: "abcd" 输出: "dcbabcd" 链接:https://leetcode-cn.com/problems/shortest-palindrome 解题记录 回文判断 通过双指针进行比对 right指针分别从后向前循环 然后获取子字符串判断是否为回文 之后补全后边即可 /** *

泛泛之素 583

使用VLC库实现视频播放器(WPF版)

使用wpf制作一个视频播放器 一、 LibVLCSharp介绍 LibVLCSharp是基于VideoLAN的LibVLC库的.NET平台的跨平台音频和视频API。它提供了一个全面的多媒体API,可以跨移动、服务器和桌面使用,以呈现视频和输出音频。支持Mono、.NET Framework和.NET核心运行时。在vs工具中,只需要安装截图中得两个nuget包。 二、视频播放器的实现 视频播放器的实现需要用到两个比较nuget包中提供的类,MediaPlayer类。MediaPlayer类型用于控

cangqiongxiaoye的博客 1万+

从零到一:Bioconductor新手入门与R包安装实战

本文详细介绍了Bioconductor在生物信息学中的重要性及其R包安装实战指南。从环境准备到BiocManager的使用,再到常见问题排查,帮助新手快速掌握这一强大工具。特别推荐org.Hs.eg.db等核心工具包,助力基因注释和功能分析,提升研究效率。

weixin_29061041的博客 418

力扣---2020.8.29

214. 最短回文串 class Solution { public String shortestPalindrome(String s) { String ss = s + new StringBuilder(s).reverse().toString(); for (int i=s.length(),j=i; i>0; i--,j++) { if (ss.substring(0, i).equals(ss.substring(j))

Carroll的博客 378

在Allegro设计界面中如何修改封装焊盘

在高密度板的情况下,SUIPLA(支持内层没有的焊盘摘掉)打勾,在高密度板的情况下,内层没有的焊盘摘掉可以增加走线的空间。3、修改完焊盘后,选择File→Update to Design(更新到设计)。然后关闭焊盘修改对话框即可。,将会定期不定期更新技术文章,互相学习交流。或者点击Options选项卡下要修改的焊盘,然后点击Edit修改。在Allegro PCB设计界面中修改封装焊盘的方法。2、然后点击封装上要修改的焊盘,右击选择Edit。修改完成后如下图所示。

bhxc809751502的博客 7806

Leetcode 214: Shortest Palindrome

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For exampl...

weixin_30657999的博客 135

深度学习笔记——前向传播与反向传播、神经网络(前馈神经网络与反馈神经网络)、常见算法概要汇总

本文简要介绍深度学习的前向传播与反向传播,以及前馈神经网络与反馈神经网络。

haopinglianlian的博客 3042

Python爬虫实战:全面采集国家自然科学基金项目数据的全流程指南

国家自然科学基金委员会(NSFC)支持基础研究、应用基础研究,是我国科研投入的核心项目之一。公开的项目数据包括项目名称、负责人、资助金额、年度、单位等,具备极高科研和数据分析价值。requests:基础HTTP请求库,简单直观:异步HTTP请求库,适合大规模并发:HTML解析,提取数据:处理JavaScript渲染网页pandas:数据分析与清洗:数据库存储:重试机制实现。

2201_76125261的博客 753

力扣刷题顺序,别人的引用一下

题目分类及刷题顺序推荐 一. 数组 题目分类题目编号数组的遍历485 最大连续 1 的个数495 提莫攻击414 第三大的数628 三个数的最大乘积统计数组中的元素645 错误的集合697 数组的度448 找到所有数组中消失的数字442 数组中重复的数据41 缺失的第一个正数274 H 指数数组的改变、移动453 最小操作次数使数组元素相等665 非递减数列283 移动零二维数组及滚动数组118 杨辉三角119 杨辉三角 II661 图片平滑器598 范围求和 II419 甲板上的战舰数组的旋转189 轮转

weixin_50517544的博客 1007

嵌入式工程师必学(9):USB 3.0协议理解

USB3.0和USB2.0相比,在线缆上从4根线(Vbus、GND、D+、D-)变为了8根线(Vbus、GND、D+、D-、SSRX+\SSRX-\SSTX+\SSTX-),可见增加的4根线都是和超速相关的,新增加的超速有两类,分别为:超速Gen1(5.0Gbps),超速+Gen2(10Gbps),还兼容USB2.0的3类速率:low-speed(1.5Mbps),full-speed(12Mbps),andhigh-speed(480Mbps)。从设计可以看出,USB3....

码农17年的博客 1万+

【leetcode】高频题目整理_字符串篇( High Frequency Problems, String )

字符串篇-95题(String, 95 problems) 截止至今LeetCode题目总量已经有`1582题`,估计将来每年平均增长`300题`左右,大部分人肯定是`刷不完的`,所以得有选择地刷LeetCode。 一种公认的刷题策略是`按类别刷题`,可是每个类别也有许多题,在有限的时间里`到底该刷哪些题呢`?个人根据`LeetCode官方`给出的每个题目的`出现频率`,整理并收录了每个类别里`高频出现`的题目,对于官方统计频率太低的题目,不予收录,最终得到了这个高频题目表格。

Liber-coder的博客 2091

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

【职业】算法与数据结构专题

做点什么

sinat_38368658的博客 1000

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

字符串变换最小字符串

题目: 给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较)。 变换规则:交换字符串中任意两个不同位置的字符。 解题思路: 1、对字符串按照字典序进行排序,找到字典序最小的字符串。 2、找到这个字符串中字典序最小的字符的位置。 3、找到字符串中第一个跟最小字符串不相同的字符的位置,然后跟第一个最小字符进行交换。 4、题目规定只能交换一次,交换后得到的就是最小字符串。 代码: function changeString(str) { .

G1useppE的博客 1927

深度学习工具包 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")

上一篇: LeetCode657-20.8.28-机器人能否返回原点
下一篇: LeetCode557-20.8.30-反转字符串的单词
RedDevill
博客等级 码龄8年 2粉丝 54原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值