344. Reverse String

本文介绍了一种简单的字符串反转方法,提供了两种实现方式:一种是通过字符串拼接的方式;另一种是通过字符数组交换位置来实现字符串的反转。这两种方法适用于不同的场景,并且在实际应用中能够有效地完成字符串反转的任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

344. Reverse String

  • Total Accepted: 159393
  • Total Submissions: 271454
  • Difficulty: Easy
  • Contributor: LeetCode

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

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

Subscribe to see which companies asked this question.

算法思路

由于测试的数据比较多,一开始想的比较简单,直接利用字符串拼接,没有考虑效率问题,最后结果超时了。
第一种方法是比较简单的方法,直接利用字符串拼接
第二种方法采用末尾和前位交换的方法,但是要注意的是要先把字符串转化为字符数组,因为在交换的过程中不能直接对字符串中的某一字符赋值,
然后返回的时候要new String对象,否则返回的是一个地址

代码一:

public static String reverse(String s){
		String result = "";
		for(int j=0; j<s.length(); j++){
			result = s.charAt(j) + result;
		}
		
		return result;
	}

代码二:

package easy;

public class ReverseString {
	public static String reverseString(String s) {
		String string = "";
		char[] result = s.toCharArray();
		char temp ;
        int i = 0;
        int j = s.length()-1;
        while(i<j){
        	temp = result[i];
        	result[i] = result[j];
        	result[j] = temp;
        	i++;
        	j--;       	
        }
        return new String(result);
	}
	public static void main(String[] args){
		System.out.println(reverseString("hello"));
	}

}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值