题目编号
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++) { if(pre == str.charAt(j)){ count++; }else{ sb.append(count).append(pre); pre = str.charAt(j); count = 1; } } sb.append(count).append(pre); str = sb.toString(); } return str; } }
|
387. 字符串中的第一个唯一字符
解题思路
用数组自创哈希表,因为只有小写字母,所以设置一个26长度的数组,字符串中出现一次,数组里对应的字母就+1,然后再对字符串的字母一一对照,如果值为1就输出,找不到1则无解。
代码
| 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; } }
|