【Leetcode】字符串

题目编号

38 387

38.外观数列

解题思路

因为后一项是前一项决定的,所以用循环来做。
选取第一个数,然后数后面有多少相同,最后用appned加上去。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public String countAndSay(int n) {
String str = "1"; // 第一个数
for (int i = 2; i <= n; i++) {
StringBuilder sb = new StringBuilder();
char pre = str.charAt(0); // 取出头部的数字
int count = 1;
for (int j = 1; j < str.length(); j++) {
// 如果后面的数与第一个相同,则count++
// 否则用append方法将头部数字的个数和头部数字加入字符串中
if(pre == str.charAt(j)){
count++;
}else{
sb.append(count).append(pre);
pre = str.charAt(j); // 选取下一个头部数字
count = 1; // count归1
}
}
// 最后跳出循环时未处理最后一个头部数字,在此在此处理
sb.append(count).append(pre);
str = sb.toString();
}
return str;
}
}

387. 字符串中的第一个唯一字符

解题思路

用数组自创哈希表,因为只有小写字母,所以设置一个26长度的数组,字符串中出现一次,数组里对应的字母就+1,然后再对字符串的字母一一对照,如果值为1就输出,找不到1则无解。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int firstUniqChar(String s) {
int count[] = new int[26];
for(int i=0;i<s.length();i++){
count[s.charAt(i)-'a']++;
}
for(int i=0;i<s.length();i++){
if(count[s.charAt(i)-'a'] == 1){
return i;
}
}
return -1;
}
}

【Leetcode】字符串
http://liuminxuan.github.io/2020/08/18/Leetcodes刷题笔记:字符串/
发布于
2020年8月18日
许可协议