leetCode 344. Reverse String 字符串

简介:

344. Reverse String

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".


思路1:

使用一个新的string来存放结果。

1
2
3
4
5
6
7
8
9
10
11
12
class  Solution {
public :
     string reverseString(string s) {
         int  len = s.size();
         string result;
         for ( int  n = 0; n < len; n++)
         {
             result.append(1,s.at(len - 1 - n));
         }
         return  result;
     }
};

思路2:

修改原来string直接得到结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
class  Solution {
public :
     string reverseString(string s) {
         int  len = s.size();
         for  ( int  i = 0; i < len / 2 ; i++)
         {
             char  a = s[i];
             s[i] = s[len - 1 - i];
             s[len - 1 - i] = a;
         }
         return  s;
     }
};




本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1836488

相关文章
|
2月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
316 100
|
2月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
425 99
|
2月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
2月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
3月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
278 92
|
4月前
|
自然语言处理 Java Apache
在Java中将String字符串转换为算术表达式并计算
具体的实现逻辑需要填写在 `Tokenizer`和 `ExpressionParser`类中,这里只提供了大概的框架。在实际实现时 `Tokenizer`应该提供分词逻辑,把输入的字符串转换成Token序列。而 `ExpressionParser`应当通过递归下降的方式依次解析
337 14
|
7月前
|
Go 索引
【LeetCode 热题100】394:字符串解码(详细解析)(Go语言版)
本文详细解析了 LeetCode 热题 394:字符串解码。题目要求对编码字符串如 `k[encoded_string]` 进行解码,其中 `encoded_string` 需重复 `k` 次。文章提供了两种解法:使用栈模拟和递归 DFS,并附有 Go 语言实现代码。栈解法通过数字栈与字符串栈记录状态,适合迭代;递归解法则利用函数调用处理嵌套结构,代码更简洁。两者时间复杂度均为 O(n),但递归需注意栈深度问题。文章还总结了解题注意事项及适用场景,帮助读者更好地掌握字符串嵌套解析技巧。
199 6
|
8月前
|
数据处理
鸿蒙开发:ArkTs字符串string
字符串类型是开发中非常重要的一个数据类型,除了上述的方法概述之外,还有String对象,正则等其他的用处,我们放到以后得篇章中讲述。
490 19