2020年的第一天,必须更新一条公众号,证明自己还在努力刷题(几周写一题),努力写公众号中。
原题地址:https://leetcode-cn.com/problems/reverse-string/
题目描述:
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
解题思路:
这题我当时使用Go语言写的,直接从两端遍历,然后一直互换内容就好了。轻松加愉快的解决一题。
中文官网题解:
https://leetcode-cn.com/problems/reverse-string/solution/
个人题解:
func reverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
结果:
15ms很靠前,虽然现在看不出来了。
接下去是第二题
原题地址:https://leetcode-cn.com/problems/string-to-integer-atoi/
题目描述:
题意很简单,最关键就是一句话:请你来实现一个 atoi
函数,使其能将字符串转换成整数。
解题思路:
中文官网题解:
https://leetcode-cn.com/problems/string-to-integer-atoi/solution/
个人题解:
public class Solution {
public int myAtoi(String str) {
if (str == null || str.length() < 1)
return 0;
str = str.trim();
char flag = '+';
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
double result = 0;
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
i++;
}
if (flag == '-')
result = -result;
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) result;
}
}
结果:
惨不忍睹的执行耗时。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有