找不同
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 *t* 由字符串 *s* 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y"
输出:"y"
示例 3:
输入:s = "a", t = "aa"
输出:"a"
示例 4:
输入:s = "ae", t = "aea"
输出:"a"
提示:
0 <= s.length <= 1000
t.length == s.length + 1
s 和 t 只包含小写字母
java
1.桶排序思想
统计两个字符串中的字母的个数,用两个26位的数组来存储;
在比较两个数组,不同的位置的数加上’a’的ascll码就是所求的添加的字母;
class Solution {
public char findTheDifference(String s, String t) {
if(s.equals("")) return t.charAt(0);
int[] bs = new int[26];
int[] ts = new int[26];
char c = 'a';
for (int i = 0; i < s.length(); i++) {
bs[s.charAt(i)-'a'] ++;
}
for (int i = 0; i < t.length(); i++) {
ts[t.charAt(i)-'a'] ++;
}
for (int i = 0; i < bs.length; i++) {
if(bs[i]!=ts[i]){
c += i;
break;
}
}
return c;
}
}ascll码值的综合的差
2.因为我们都知道,第二个字符串只比第一个字符串多了一个字母,所以用第二个字符串的ascll减去第一个字符串的ascll值即可
class Solution {
public char findTheDifference(String s, String t) {
int as = 0, at = 0;
for (int i = 0; i < s.length(); ++i) {
as += s.charAt(i);
}
for (int i = 0; i < t.length(); ++i) {
at += t.charAt(i);
}
return (char) (at - as);
}
}
python
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
str_count = [0] * 26
for ch in s:
str_count[ord(ch)-ord('a')] += 1
for ch in t:
str_count[ord(ch)-ord('a')] -= 1
if str_count[ord(ch)-ord('a')] < 0:
return ch
return ''
旋转图像
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
说明:
你必须在**原地**旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
示例 2:
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
java
用一个辅助数组先存贮然后再替换原数组
class Solution {
public void rotate(int[][] matrix) {
int[][] a= rotate1(matrix);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
matrix[i][j] = a[i][j];
}
}
}
public static int[][] rotate1(int[][] matrix){
int[][] rotate = new int[matrix.length][matrix.length];
int len = matrix.length;
for (int i = 0; i < matrix.length; i++) {
int[] a = matrix[i];
for (int j = 0; j < a.length; j++) {
rotate[j][len-1] = a[j];
}
len--;
}
return rotate;
}
}
python
原地替换
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
left,top,right,bottom = 0,0,n-1,n-1
while left<right:
for i in range(left,right):
matrix[top][i],matrix[i][right],matrix[bottom][n-1-i],matrix[n-1-i][left] = matrix[n-1-i][left],matrix[top][i],matrix[i][right],matrix[bottom][n-1-i]
left += 1
right -= 1
top += 1
bottom -= 1