字符串切片反转字符串

Can you write a function that reverses an inputted string without using the built-in Array#reverse method?

您是否可以编写一个无需使用内置Array#reverse方法即可反转输入字符串的函数?

Let’s look at some examples. So, calling:

让我们看一些例子。 因此,致电:

reverseString("jake") should return "ekaj".

reverseString("jake")应该返回"ekaj"

reverseString("reverseastring") should return "gnirtsaesrever".

reverseString("reverseastring")应该返回"gnirtsaesrever"

This lesson was originally published at https://algodaily.com, where I maintain a technical interview course and write think-pieces for ambitious developers.

本课程最初在 https://algodaily.com上 发布 ,我 那里维护技术面试课程,并为雄心勃勃的开发人员撰写思想著作。

对或错? (True or False?)

In Java, C#, JavaScript, Python and Go, strings are immutable. This means the string object's state can't be changed after creation.

在Java,C#,JavaScript,Python和Go中,字符串是immutable 。 这意味着在创建后无法更改字符串对象的状态。

Solution: True

解决方案:正确

演示地址

采访者心态 (On Interviewer Mindset)

Reversing a string is one of the most common technical interview questions that candidates get. Interviewers love it because it’s deceptively simple. After all, as a software engineer, you’d probably call the #reverse method on your favorite String class and call it a day!

反转字符串是考生最常见的技术面试问题之一。 采访者喜欢它,因为它看似简单。 毕竟,作为一名软件工程师,您可能会在自己喜欢的String类上调用#reverse方法并每天调用它!

So don’t overlook this one — it appears a surprising amount as a warm-up or build-up question. Many interviewers will take the approach of using an easy question like this one, and actually judge much more harshly. You’ll want to make you sure really nail this.

因此,请不要忽视这一点-它似乎是一个令人惊讶的热身或堆积问题。 许多面试官会采用这样一个简单的问题,实际上会做出更严厉的判断。 您需要确保确实做到这一点。

我们将如何开始解决 (How We’ll Begin Solving)

We want the string reversed, which means that we end up with all our letters positioned backwards. If you need a quick review of strings, check out our lesson on arrays and strings.

我们希望字符串反转 ,这意味着我们最终将所有字母都向后放置。 如果您需要快速查看 string ,请阅读 有关数组和string的课程

We know that strings can be thought of as character arrays-- that is, each element in the array is a single character. And if we can assume that, then we know the location (array position) of each character, as well as the index when the array ends.

我们知道string s可以被认为是字符数组-也就是说,数组中的每个元素都是单个字符。 而且,如果可以假设,那么我们就知道每个字符的位置(数组位置)以及array结束时的索引。

There’s a caveat to thinking of strings as character arrays — it’s not always true. As readers and viewers have pointed out, a string represents text formed from graphemes (the smallest functional unit of a writing system) — formed by combining character sequences in unicode.

需要将字符串视为字符数组,但并非总是如此。 正如读者和观众所指出的那样,字符串代表由字素(书写系统的最小功能单元)形成的文本,该字素是通过以Unicode组合字符序列而形成的。

Though strings and arrays contain similar methods like length, concat, and character position access-- they are not identical. As an example, arrays are mutable and strings usually are not. Before we can operate on the string as an array, we'll need to separate the units (in JS by calling the .split() method, or bypass this property by generating a brand new string instead of trying to operate on the original.

尽管字符串和数组包含类似的方法,例如lengthconcat和字符位置访问- 但它们并不相同 。 例如,数组是可变的,而字符串通常不是可变的。 在将字符串作为数组进行操作之前,我们需要分隔单元(在JS中,通过调用.split()方法,或通过生成全新的字符串来绕过此属性,而不是尝试对原始字符串进行操作)。

However, after the split operation, we can apply that paradigm to operating on this string. Thus we can step through each of its indices. Stepping through the beginning of the string, we’ll make these observations at each point:

但是,在split操作之后,我们可以将该范例应用于对该字符串的操作。 因此,我们可以逐步浏览其每个索引。 逐步浏览字符串的开头,我们将在每个点进行以下观察:

const str = "JAKE";// position 0 - "J"// position 1 - "A"// ...

Since a reversed string is just itself backwards, a brute force solution could be to use the indices, and iterate from the back to the front.

由于反向字符串本身本身就是向后的,因此蛮力解决方案可能是使用索引,并从后向前迭代。

See the code attached and try to run it using Run Sample Code. You'll see that we log out each character from the back of the string!

请参阅随附的代码,并尝试使用Run Sample Code运行它。 您会看到我们从字符串的后面注销了每个字符!

function reverseString(str) {  let newString = '';  // start from end  for (let i = str.length-1; i >= 0; i--) {    console.log('Processing ', newString, str[i]);    // append it to the string builder    newString = newString + str[i];  }  // return the string  return newString;}console.log(reverseString('test'));

填写 (Fill In)

We want to console.log out:

我们要console.log注销:

54321

What’s the missing line here?

这里缺少什么?

var arr =  [1, 2, 3, 4, 5];for (var i = ___________; i >= 0; i--) {    console.log(arr[i]);}

Solution: arr.length — 1

解决方案: arr.length — 1

我们能比蛮力做得更好吗? (Can We Do Better Than Brute Force?)

However, it wouldn’t really be an interesting algorithms question if there wasn’t a better way. Let’s see how we can optimize this, or make it run faster. When trying to make something more efficient, it helps to think of things to cut or reduce.

但是,如果没有更好的方法,这实际上不是一个有趣的算法问题。 让我们看看如何优化它或使其运行更快。 当试图使某事更有效率时,考虑减少或减少的事情会有所帮助。

One thing to note is that we’re going through the entire string — do we truly need to iterate through every single letter?

需要注意的一件事是,我们要遍历整个字符串-我们是否真的需要遍历每个字母?

Let’s examine a worst case scenario. What if the string is a million characters long? That would be a million operations to work through! Can we improve it?

让我们研究一个最坏的情况。 如果字符串长度为一百万个字符怎么办? 这将需要进行一百万次操作! 我们可以改善吗?

是的,具有更多指针! (Yes, With More Pointers!)

Well, we’re only working with a single pointer right now. The iterator from our loop starts from the back, and appends each character to a new string, one by one. Having gone through The Two Pointer Technique, we may recognize that some dramatic improvements can be had by increasing the number of pointers we use.

好吧,我们现在仅使用单个指针。 循环中的迭代器从后面开始,并将每个字符一个接一个地追加到新字符串中。 经历了两次指针技术之后 ,我们可能会认识到,通过增加使用的指针数量,可以取得一些显着的改进。

By this I mean, we can cut the number of operations in half. How? What if we did some swapping instead? By using a while loop and two pointers-- one on the left and one on the right.

我的意思是,我们可以将操作数量减少一半 。 怎么样? 如果我们进行一些交换该怎么办? 通过使用while循环和两个指针-一个在左侧,一个在右侧。

With this in mind — the big reveal is that, at each iteration, we can swap the letters at the pointer indices. After swapping, we would increment the left pointer while decrementing the right one. That could be hard to visualize, so let's see a basic example listed out.

考虑到这一点,最大的启示是,在每次迭代中,我们都可以在指针索引处交换字母。 交换之后,我们将增加left指针,同时减少right指针。 这可能很难想象,所以让我们看一下列出的基本示例。

jake    // starting stringeakj    // first pass^  ^ekaj    // second pass ^^

多项选择 (Multiple Choice)

What’s a good use case for the two pointers technique?

两个指针技术的一个好用例是什么?

  • Shifting indices to be greater at each iteration每次迭代的移位指数都更大
  • Reducing a solution with a nested for-loop and O(n²) complexity to O(n)将嵌套循环和O(n²)复杂度降低为O(n)的解决方案
  • Finding pairs and duplicates in a for-loop在for循环中查找对和重复项
  • None of these都不是

Solution: Reducing a solution with a nested for-loop and O(n²) complexity to O(n)

解决方案:将嵌套的for循环和O(n²)复杂度的解决方案简化为O(n)

With two pointers, we’ve cut the number of operations in half. It’s much faster now! However, similar to the brute force, the time complexity is still O(n).

使用两个指针,我们将操作数减少了一半。 现在要快得多! 但是,类似于蛮力,时间复杂度仍然是O(n)

为什么是这样? (Why Is This?)

Well, if n is the length of the string, we'll end up making n/2 swaps. But remember, Big O Notation isn't about the raw number of operations required for an algorithm-- it's about how the number scales with the input.

好吧,如果n是字符串的长度,我们最终将进行n/2交换。 但是请记住, Big O表示法与算法所需的原始操作数无关,而是与输入数如何缩放有关

So despite requiring half the number operations — a 4-character string would require 2 swaps with the two-pointer method. But an 8-character string would require 4 swaps. The input doubled, and so did the number of operations.

因此,尽管只需要执行一半的数字运算,但一个4字符的字符串将需要使用两指针方法进行2交换。 但是8字符的字符串将需要进行4交换。 输入增加了一倍,操作数也增加了。

最终解决方案 (Final Solution)

function reverseString(str) {  let strArr = str.split("");  let start = 0;  let end = str.length - 1;  while (start <= end) {    const temp = strArr[start];    strArr[start] = strArr[end];    strArr[end] = temp;    start++;    end--;  }  return strArr.join("");}

Originally published at https://algodaily.com on August 19, 2020.

最初于 2020年8月19日 发布在 https://algodaily.com 上。

翻译自: https://medium.com/swlh/how-to-reverse-a-string-16a2acc1dab8

字符串切片反转字符串


http://www.taodudu.cc/news/show-4621420.html

相关文章:

  • keras 香草编码器_用香草javascript遍历dom
  • 知乎电商创业准备_你准备参加早期创业了吗
  • learnpythonthehardway.org_Python学习笔记LearnPythonHardWay
  • 百余大佬署名AI论文被爆抄袭!智源现已致歉
  • SitePoint播客#65:是否拥有IE6?
  • java.lang.StringIndexOutOfBoundsException: String index out of range: -1
  • Servlet中的监听器与过滤器的详细介绍
  • 《出版专业基础》2015年版(初级)思考与练习 第五章
  • 看诸葛亮是如何识别对付小人的~
  • 简单的html登录注册页面
  • 注册页面reg.html
  • HTML+CSS+JavaScript 实现登录注册页面(超炫酷)
  • 前端案例 ——注册页面(html+css实现)
  • HTML 简单实现注册页面
  • vue 网格组件_简单的Vue组件可显示带有事件的月网格日历
  • figma下载_在Figma中将约束与布局网格一起使用
  • Halcon 《ML_MLP》网格缺陷检测
  • puzzle(1311)点亮所有的灯
  • html表格去除网格线_HTML表格模式:数据网格
  • he/she, him/her 和 his/hers 等等的使用
  • UE4物理模块分析
  • element-ui 网格_UI备忘单:列表与网格
  • OPenGL 学习笔记之 Mesh 网格知识
  • English trip V1 - 10.Family Ties 家庭关系 Teacher:Emily Key: Possessive s (所有格 s)
  • Matlab 网格剖分程序DistMesh函数指南
  • 冯诺依曼 计算机名言,约翰·冯·诺伊曼留给我们的名言之一
  • 计算机科学家的名言警句,有关写数学的名言警句
  • 典范杜希奇与机器人_典范英语8-16doohickey and the robot杜希奇与机器人
  • 杜拉拉升职记1-学习笔记
  • 【观察】打造中国“酷公司”新标杆,联想陪伴中小企业共同成长

字符串切片反转字符串_如何反转字符串相关推荐

  1. pandas 字符串切片后保存_我擦~字符串转字节切片后,切片的容量竟然千奇百怪...

    以下文章来源于新世界杂货铺 ,作者许文 新世界杂货铺 作为一名Gopher, 我愿称之为Go的干(杂)货铺子! 神奇的现象 切片, 切片, 又是切片! 今天遇到的神奇问题和切片有关, 具体怎么个神奇法 ...

  2. pandas 字符串切片后保存_pandas:快速处理字符串方法

    前言 当我们遇到一个超级大的DataFrame,里面有一列类型为字符串,要将每一行的字符串都用同一方式进行处理,一般会想到遍历整合DataFrame,但是如果直接这样做的话将会耗费很长时间,有时几个小 ...

  3. python中字符串切片取奇数_Python中的字符串切片(截取字符串)的详解

    Python中的字符串切片(截取字符串)的详解 字符串索引示意图 字符串切片也就是截取字符串,取子串 Python中字符串切片方法 字符串[开始索引:结束索引:步长] 切取字符串为开始索引到结束索引- ...

  4. c语言 字符串切片重组成完整,完美分割字符串,实现字符串的splict功能

    class Str:Client_C { string val; string[] str = new string[100]; public void StrT1() { //1.正常情况 //2. ...

  5. 字符串删除重复字符_高效的字符串清理-删除内部重复空间

    字符串删除重复字符 介绍 (Introduction) 我经常回答一些问题,其中的字符串需要"清除"多个空格字符. 最常见的解决方法是删除前导或尾随空格. 对于这个问题,有非常方便 ...

  6. string字符串数字自增_常见的字符串操作

    一部分字符串操作的总结,比较基础.目录: 使用str.split() 切分数据 将 datetime 类型转化为字符串类型 字符串的合并操作 使用 str.strip() 去除字符串前面和后面所有的字 ...

  7. c字符串分割成数组_数组与字符串

    定义数组时,应该注意以下几点: (1) 数组使用的是方括号[ ],不要误写成小括号( ). (2) 常量表达式的值必须是一个正整数值,不能含有变量,但是可以是符号常数或常量表达式. (3) 数组定义后 ...

  8. python数字字符串和数字相加_数字和字符串

    数字和字符串 本节我们将了解最基础的数据类型,数字和字符串.打开你的Python REPL并写出以下语句. >>> a = 2 >>> type(a) >&g ...

  9. c语言 字符串切片重组,C语言实现分割字符串

    背景 遇到一个将字符串分割场景.以前从没有用c语言实现,都是使用python的split()函数,python处理起来很简单. split()方法语法: str.split(str="&qu ...

  10. python 字符串可以直接连接吗_如何连接字符串。。。在?(Python)

    其他人已经指出了您的错误消息的原因.我已经冒昧地重新编写了代码.我所做的主要工作是避免字符串连接-在Python中,字符串是不可变的,因此连接需要创建一个完整的新字符串.避免这种情况的一种常见方法是将 ...

最新文章

  1. mycheckpoint
  2. android 反编译apktool工具
  3. 领航的公开课 有空可以看看
  4. innerHTML,innerText
  5. python笔试编程题_Python——面试编程题
  6. onclick控制元素显示与隐藏时,点击第一次无反应的原因
  7. colorWithPatternImage, stretchableImageWithLeftCapWidth
  8. (SWAT-3)SWAT土壤数据库的建立
  9. 羡慕的核心是焦虑_焦虑是自由的头晕
  10. java中常用的摘要算法
  11. 电子计算机的两个重要改进是,1946年,冯.诺依曼在研制EDVAC计算机时,提出的两个重要改进是什么?...
  12. mysql relay_mysql relay log参数汇总
  13. docker--privileged
  14. DTP加载/ODS激活时持续黄灯的解决办法
  15. XShell4 SSH服务器拒绝了密码解决办法
  16. markdown语法总结
  17. Java中IO流(3).
  18. 图像处理术语解释:灰度、色相、饱和度、亮度、明度、阿尔法通道、HSL、HSV、RGBA、ARGB和PRGBA以及Premultiplied Alpha(Alpha预乘)等基础概念详解
  19. PCSX2的impossible blend释疑
  20. 刘易远:一个人在发财之前必须做出4个改变

热门文章

  1. 从包工头到程序猿(三)味道
  2. 酒店预订系统源码c语言,HotelManage - 源码下载|系统编程|源代码 - 源码中国
  3. linux番茄时钟,Linux 番茄时钟 定时 取消 快捷方式
  4. 对qps、tps、rt、并发数、吞吐量、限流、熔断和降级的了解
  5. 图像处理之天空区域识别
  6. 模拟一个类似LinkedList的集合
  7. JVM原理讲解和调优
  8. c语言程序与设计教学设计,浅谈C语言程序设计课程的教学设计
  9. 怎么输入版权符号(?)
  10. 关于时间、物质结构、四维空间的猜想