leetcode 1202. Smallest String With Swaps(交换得到最小的字符串)

Kafka延迟队列实现方案全解析 $ \text{时间轮} = \text{环形数组} + \text{分层设计} $$需要补充代码实例或特定场景的优化方案可进一步细化,此大纲已覆盖核心技术路径。 阅读详情

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.

You can swap the characters at any pair of indices in the given pairs any number of times.

Return the lexicographically smallest string that s can be changed to after using the swaps.

Example 1:

Input: s = “dcab”, pairs = [[0,3],[1,2]]
Output: “bacd”
Explaination:
Swap s[0] and s[3], s = “bcad”
Swap s[1] and s[2], s = “bacd”
Example 2:

Input: s = “dcab”, pairs = [[0,3],[1,2],[0,2]]
Output: “abcd”
Explaination:
Swap s[0] and s[3], s = “bcad”
Swap s[0] and s[2], s = “acbd”
Swap s[1] and s[2], s = “abcd”

给一个字符串s,pairs里面是一对对的数,每一对表示这两个下标对应的字符可以交换位置。
而且可以无限次交换。

问如何利用这些交换使得字符串在字典顺序上最小。

思路:

乍一看像是字符串的问题,实则是graph问题。

把连续的可以交换的点看成一个连通区域,那么这个区域内任意两点都是可以交换的(因为不限制交换次数,总有办法把它们换到想去的地方)。
比如上面example1, 0和3,0和2,1和2可以交换,连在一起就是0,1,2,3可以互换。
既然可以互换,那么就按字典顺序最小的给对应的字符排个序,把排过序的字符插入到排过序的对应下标处,变成了"abcd"。

所以需要解决两个问题:
1)找连通区域。
2)把连通区域内的下标和字符排序,排好序的字符放在排好序的下标处。

方法1:
DFS
找连通区域可以通过建立无向图(邻接链表的形式),用DFS把相连的下标(可以交换的下标)放到一个list,
同时把对应的字符也放入list。

然后对这两个list排序,把排好序的字符放入排好序的下标处。
(因为取出的下标就是这些字符的位置,字符已经按字典顺序排好,要从左往右依次放入排好序的字符,所以这些下标也要排序)。

class Solution {
    List<Integer>[] graph;
    boolean[] visited;
        
    public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
        int n = s.length();
        visited = new boolean[n]; 
        graph = new ArrayList[n];
        char[] res = new char[n];
        
        for(int i = 0; i < n; i++) {
            graph[i] = new ArrayList<Integer>();
        }
        
        //构建无向图
        for(List<Integer> pair : pairs) {
            graph[pair.get(0)].add(pair.get(1));
            graph[pair.get(1)].add(pair.get(0));
        }
        
        //遍历每个顶点,找连通区域
        for(int i = 0; i < n; i++) {
            if(visited[i]) continue;
            
            //每个装的都是一个连通区域          
            List<Character> chars = new ArrayList<>();
            List<Integer> ids = new ArrayList<>();
            dfs(s, i, chars, ids);
            
            //把获得到的连通区字符和下标排序,按下标把字符插入到string数组中
            Collections.sort(chars);
            Collections.sort(ids);
            
            for(int j = 0; j < ids.size(); j++) {
                res[ids.get(j)] = chars.get(j);
            }
        }
        
        return new String(res);
    }
    
    void dfs(String s, int idx, List<Character> chars, List<Integer> ids) {
        if(visited[idx]) return;
        chars.add(s.charAt(idx));
        ids.add(idx);
        
        visited[idx] = true;
        
        for(int adj : graph[idx]) {
            dfs(s, adj, chars, ids);
        }
    }
}

方法2:
Union Find
找连通区域还可以用union-find方法,
简单说下,union就类似于聚类,每个可交换的点(有边相连的点)顺藤摸瓜找到它的root,
所以这些点就聚成以root为首的类,把同一类的点直接接到root下面。
下次检索类别的时候就不需要再通过 点1,点2,点3…来找到root,而可以一步找到root。缩短了时间。

find类似于检索,就是找到每个点所属的root。

同一root的点就是一个连通区域。

下面是UnionFind类
rank表示一个root下有多少个点,当然聚类是往点多的类去靠拢。

class UnionFind {
    int[] root;
    int[] rank;
    
    public UnionFind(int n) {
        root = new int[n];
        rank = new int[n];
        
        for(int i = 0; i < n; i++) {
            root[i] = i;
            rank[i] = 1;
        }
    }    
    
    int find(int node) {
        if(node == root[node]) return node;
        return root[node] = find(root[node]);
    }
    
    void union(int n1, int n2) {
        int r1 = find(n1);
        int r2 = find(n2);
        
        //不是同一个root,要union
        if(r1 != r2) {
            if(rank[r1] >= rank[r2]) {
                root[r2] = r1;
                rank[r2] += rank[r1];
            } else {
                root[r1] = r2;
                rank[r1] += rank[r2];
            }
        }
    }
}

然后思路就和上面DFS差不多,也是先找连通区域,存入连通区的下标和字符。
然后排序,注意这里不需要给下标排序,因为下标存入的时候是按顺序访问的。
只需要给字符排序,放入对应的下标中。

这个方法比DFS快很多。

    public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
        int n = s.length();
        UnionFind uf = new UnionFind(n);
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        char[] res = new char[n];
        
        for(List<Integer> pair : pairs) {
            uf.union(pair.get(0), pair.get(1));
        }
        
        for(int i = 0; i < n; i++) {
            int root = uf.find(i);
            map.putIfAbsent(root, new ArrayList<Integer>());
            map.get(root).add(i);  //按下标顺序加的,所以连通区的下标已经是排好序的
        }
        
        for(List<Integer> ids : map.values()) {
            char[] chars = new char[ids.size()]; //利用和下标数量一样直接建立数组,比ArrayList快很多
            for(int i = 0; i < ids.size(); i++) {
                chars[i] = s.charAt(ids.get(i));
            }
            
            Arrays.sort(chars);
            for(int i = 0; i < ids.size(); i ++) {
                res[ids.get(i)] = chars[i];
            }
        }
        return new String(res);
    }   
}
NVIDIA DGX Spark实战:如何在桌面上轻松运行200B参数大模型(附配置教程) 本文提供了NVIDIA DGX Spark在桌面端运行200B参数大模型的完整实战指南。详细介绍了从硬件初始化、系统配置、容器化环境搭建,到模型加载、量化、推理流水线编写及性能调优的全过程。重点阐述了如何利用其统一内存架构和TensorRT-LLM等工具进行高效本地推理,并探讨了通过双机互联扩展以应对超大规模模型的方法。 阅读详情

相关推荐

channel || channelGroup || ctx.writeAndFlush()发送字符串消息客户端接收不到的原因

一、原因 网络上传播的数据都是字节(二进制数据)类型。我们如果直接向网络流里面写入一个对象(如:String对象),是无法传输的。只有将对象序列化(转换为可以传输的字节类型)之后,才可以进行传输。所以问题的根源就很清楚了,需要把字符串转换成字节进行传输。、 二、解决办法 1、手动序列化 服务端: channelGroup.writeAndFlush(Unpooled.copiedBuffer("【客户端】"+remoteAddress+"已下线"+format.format(new Date()), Cha

haohaoxuexiyai的博客 4072

ASCII排序 nyoj4

#include void swap(char &a,char &b) { char temp = a; a = b; b = temp; } int main() { int i = 0; scanf("%d",&i); while(i--) { char s[10]; scanf("%s",&s); if(s[0] > s[1])swap(s[0],s[1

脚踏实地,仰望星空 456

c语言播放背景音乐

相信很多童鞋都在为大学课设而伤透头脑,而背景音乐的使用无疑会成为其中的一个亮点(总比没有好吧(╯▽╰)),故接下来我将介绍一下如何用C播放音乐。我用的编译器是CodeBlocks16.01接下来新建一个C文件建立完后是这样滴然后添加其中mciSendString()函数是由&lt;mmsystem.h&gt;库提供的供播放音乐(MP3)的函数第一个参数是歌曲所在的绝对路径 打开音乐所在位置 复制这...

qq_41443987的博客 3万+

【LeetCode】1202. Smallest String With Swaps 交换字符串中的元素(Medium)(JAVA)每日一题

【LeetCode】1202. Smallest String With Swaps 交换字符串中的元素(Medium)(JAVA) 题目地址: https://leetcode.com/problems/smallest-string-with-swaps/ 题目描述: You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a,

qq_16927853的博客 349

制作Ubuntu22.04启动盘

现在越来越多程序代码都需要运行在linux环境下,运行这些代码的前提是安装一个稳定的linux操作系统。本文选择Ubuntu 22.04去制作系统启动盘。本文主要对ubuntu22.04的启动盘制作过程进行了详细的说明,希望能帮助到有需要的朋友。

lyx_ok的博客 1万+

基于深度学习实现实时视频目标检测

实时视频目标检测是计算机视觉领域的研究热点之一,其应用场景包括智能监控、自动驾驶、机器人视觉等多个领域。深度学习技术的快速发展使得实时视频目标检测变得更加可行和准确。本文提出一种基于深度学习实现的实时视频目标检测系统,使用Python和OpenCV作为开发工具,具有高效、准确和实时的特点。 本系统的主要需求是实现实时视频目标检测功能,可以在不同的应用场景中使用。具体的需求如下:2.1 视频输入本系统需要从摄像头或视频文件中获取实时视频流,并对视频流中的目标进行检测和跟踪。2.2 目标检测本系统需要使用深度学

分享毕业设计的案例和论文 1955

1202. Smallest String With Swaps

You are given a strings, and an array of pairs of indices in the stringpairswherepairs[i] =[a, b]indicates 2 indices(0-indexed) of the string. You canswap the characters at any pair of indices...

Do not mess it up 450

中兴FTTR光猫变简易OLT:低成本搭建全光监控与局域网实战指南

本文详细介绍了如何将中兴FTTR光猫改造为简易OLT设备,实现低成本全光监控与局域网扩展。通过LOID认证、桥接模式设置及终端数破解,用户可利用二手设备搭建高性能光纤网络,适用于远程监控和长距离组网场景,显著降低部署成本。

chair的专栏 2129

798. Smallest Rotation with Highest Score

Given an array A, we may rotate it by a non-negative integer K so that the array becomes A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1].  Afterward, any entries that are less than ...

Do not mess it up 764

jmeter小白下载安装步骤

本文仅仅简单介绍了jmeter工具的下载安装,以及基础的操作步骤。

昔年@曦的博客 3545

软件安装管家matlab教程,timesat软件怎么安装 timesat安装使用图文教程 - 驱动管家...

TimeSat是一款不错的时间序列滤波软件,很专业,在提取植被物候参数方面有着很好的应用,本文主要讲解TimeSat 3.1软件在Windows和Matlab平台的安装及TimeSat 3.1软件的使用和说明详解。一、TimeSat 3.1软件安装;本文讲解TimeSat 3.1软件在Windows和Matlab平台的安装。1、打开Matlab 2011,点击菜单中的File→Set Path,如...

weixin_42112894的博客 1980

LeetCode周赛155

1200. Minimum Absolute Difference[1200.MinimumAbsoluteDifference] 最小绝对差,遍历找出最小差,插入vector即可。 class Solution { public: vector<vector<int>> minimumAbsDifference(vector<int>& arr)...

麻花不好吃 274

135、高通 ChromaTix 调优工具入门:参数含义、调优流程与效果对比

本文介绍了高通ChromaTix色彩调优工具的核心使用要点:1. ChromaTix是位于ISP管线中的色彩处理系统,核心任务是将原始色彩映射为符合人眼感知的"舒适"效果;2. 重点解析了饱和度、色调、亮度相关饱和度等关键参数的实际含义和调试陷阱;3. 分享了四步调优流程,强调需要基于多场景数据验证;4. 通过案例展示了参数调整带来的色彩改善效果;5. 总结了实用建议,包括保持单一变量调试、量化评估色差、关注极端场景表现等。文章指出ChromaTix调优是平衡不同场景需求的"妥协艺术",需要结合客观数据和主

sundong_81的博客 118

字符串this大于字符串that_【LeetCode】1202. 交换字符串中的元素

【LeetCode】1202. Smallest String With Swaps 交换字符串中的元素(Medium)(JAVA)题目描述:You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0...

weixin_33250328的博客 275

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

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

[leetcode] 1202. Smallest String With Swaps

Description You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Retu

Learning from the mistakes 277

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

LeetCode 1202. Smallest String With Swaps

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexic

Tech in Pieces 413

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Leetcode-1202. 交换字符串中的元素 Smallest String With Swaps (并查集/DFS) -超详细python

题目 给你一个字符串 s,以及该字符串中的一些「索引对」数组 pairs,其中 pairs[i] = [a, b] 表示字符串中的两个索引(编号从 0 开始)。 你可以 任意多次交换 在 pairs 中任意一对索引处的字符。 返回在经过若干次交换后,s 可以变成的按字典序最小的字符串。 链接:https://leetcode.com/problems/smallest-string-with-swaps/ You are given a string s, and an array of pairs o

JamieLuo的博客 459

【Leetcode】1202. Smallest String With Swaps

排序,接着我们只需要按照字典序回填即可。为了加快速度,我们可以用vector存储每一组下标,然后逆序排序,最后从尾部插入。的排列都能实现,由基于交换的排序的算法可以证明),那么我们可以在每个连通块内部将下标排序,按照。问经过任意次互换之后能得到的最小字典序的字符串是什么。阶图能视为若干连通块的并(因为有这么个定理,如果。允许做任意次将两个元素交换的话,任何。将能交换的下标看成图的点,那么。

数学、算法爱好者的博客 147

LeetCode 1202 Smallest String With Swaps

思路 首先要能想到并且发现,对于任何相连的,或者说在一棵树上pairs,比如[[0, 1], [0, 2], [1, 3], [1, 5], [2, 4], [2, 6]],他们可以通过交换产生任意顺序的排列。证明的方法可以通过表示成树的形式然后分析。简单来说,对于任何两个一棵树上的pair[u, v],都可以通过先将u交换到v,再反过来将v换到原来u的位置实现互换。例如[[0, 1], [0, 3]],1和3互换可以通过swap(0, 1), swap(1, 3), swap(3, 0)来实现。 有了上述

EricJeffrey的博客 190

[leetcode题解] 第1202题Smallest String With Swaps

https://leetcode-cn.com/problems/smallest-string-with-swaps/ 文章目录分析解法并查集排序思路一排序思路二排序思路三 分析 需要把这道题看成图论的题目才好做:将字符串中的索引视为图的节点,一个pair对意味着两个节点之间存在一条无向边。那么答案就可以这样来得到:对无向图中的每个连通分量所代表的字符串分别进行排序,再把字符按照索引填入原位置。 这是因为交换具有传递性,即a与b可交换,b与c可交换,那么a一定可与c交换(交换次数不受限制)。因此在连通分量

chenf1999的博客 302

LeetCode_UnionFind_1202. Smallest String With Swaps 交换字符串中的元素【并查集】【java】【中等】

LeetCode_UnionFind_1202. Smallest String With Swaps 交换字符串中的元素【并查集】【java】【中等】

&再见萤火虫&的博客 618

LeetCode //C - 1202. Smallest String With Swaps

Summary: This problem involves finding the lexicographically smallest string achievable by swapping characters at given indices any number of times. The key idea is to use Union-Find to group all swappable indices into connected components. Characters with

Made in Code 384

并查集系列:1202 Smallest String With Swaps

Smallest String With Swaps You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number

WULH 887

【并查集】leetcode1202. Smallest String With Swaps

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.You can swap t...

weixin_41348775的博客 162

LeetCode:1202. Smallest String With Swaps交换字符串中的元素(C语言)

题目描述: 给你一个字符串 s,以及该字符串中的一些「索引对」数组 pairs,其中 pairs[i] = [a, b] 表示字符串中的两个索引(编号从 0 开始)。 你可以 任意多次交换 在 pairs 中任意一对索引处的字符。 返回在经过若干次交换后,s 可以变成的按字典序最小的字符串。 示例 1: 输入:s = “dcab”, pairs = [[0,3],[1,2]] 输出:“bacd” 解释: 交换 s[0] 和 s[3], s = “bcad” 交换 s[1] 和 s[2], s = “bacd

C/C++攻城狮 423

c语言交换字符串中元素顺序,LeetCode:1202. Smallest String With Swaps交换字符串中的元素(C语言)...

题目描述:给你一个字符串 s,以及该字符串中的一些「索引对」数组 pairs,其中 pairs[i] = [a, b] 表示字符串中的两个索引(编号从 0 开始)。你可以 任意多次交换 在 pairs 中任意一对索引处的字符。返回在经过若干次交换后,s 可以变成的按字典序最小的字符串。示例 1:输入:s = “dcab”, pairs = [[0,3],[1,2]]输出:“bacd”解释:交换 s...

weixin_26741253的博客 458
上一篇: cpp namespace
下一篇: leetcode 1631. Path With Minimum Effort(最小消耗路径)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址