求字符串中第一个没有重复的字符
###题目描述
Given a string s
, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'
.
Example
For
s = "abacabad"
, the output should befirstNotRepeatingCharacter(s) = 'c'
.There are
2
non-repeating characters in the string:'c'
and'd'
. Returnc
since it appears in the string first.For
s = "abacabaabacaba"
, the output should befirstNotRepeatingCharacter(s) = '_'
.There are no characters in this string that do not repeat.
Input/Output
[execution time limit] 4 seconds (js)
[input] string s
A string that contains only lowercase English letters.
Guaranteed constraints:
1 ≤ s.length ≤ 105
.[output] char
The first non-repeating character in
s
, or'_'
if there are no characters that do not repeat.
###解法
- 暴力解法:
两层循环,很低效
1 | function firstNotRepeatingCharacter1(s) { |
因为字母的数目是确定的,其实还可以借助哈希表来做
- 简单解法:
1 | //只需要一层循环 |
难点在于lastIndexOf和indexOf两个 API不知道,一个是求出最后一次出现的索引值, 一个是首次出现的 index, 两个 索引值相同表明该元素只出现了一次
##将数组顺时针旋转90度
题目描述
You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise).
Example
For
1 | a = [[1, 2, 3], |
the output should be
1 | rotateImage(a) = |
Input/Output
[execution time limit] 4 seconds (js)
[input] array.array.integer a
Guaranteed constraints:
1 ≤ a.length ≤ 100
,a[i].length = a.length
,1 ≤ a[i][j] ≤ 104
.[output] array.array.integer
解法
1 | function rotateImage(a) { |
仔细观察row[j] = a[n-1-j][i]
,其实可以看成row[i][j] = a[n-1-j][i]
,
所以:
1 | //评分最高的方法 |
值得注意的是:
1 | a[i][j] ^= a[j][i] |
不使用中间值,交换两个数的值
所有不使用临时变量的思路都是让其中一个变量变成一个a和b都有关系的值这样可以先改变另一个变量值,最后改变原修改的变量值