151. 翻转字符串里的单词
从后向前遍历 遇到空格就跳 设置两个指针 包括有效字符串 StringBuilder 的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public String reverseWords(String s) { int len = s.length(); StringBuilder sb = new StringBuilder();
for(int i=len-1;i>=0;i--){ if(s.charAt(i)==' ') continue; int end = i+1; while(i>=0&&s.charAt(i)!=' ') i--; int start = i+1; for(int j=start;j<end;j++){ sb.append(s.charAt(j)); } sb.append(' '); } sb.deleteCharAt(sb.length()-1); return sb.toString(); } }
|
238. 除自身以外数组的乘积
方法一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int[] productExceptSelf(int[] nums) { int len = nums.length; int R[] = new int[len]; int L[] = new int[len]; int res[] = new int[len]; L[0]=1; for(int i=1;i<len;i++){ L[i] = L[i-1]*nums[i-1]; }
R[len-1] = 1; for(int j = len-2;j>=0;j--){ R[j] = R[j+1]*nums[j+1]; }
for(int i=0;i<len;i++){ res[i] = R[i]*L[i]; } return res; } }
|
方法二 处理右侧乘积时 不用再存数组了 直接累乘
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public int[] productExceptSelf(int[] nums) { int len = nums.length; int answer[] = new int[len]; answer[0]=1; int temp=1; for(int i=1;i<len;i++){ answer[i] = answer[i-1]*nums[i-1]; } for(int j=len-2;j>=0;j--){ temp*=nums[j+1]; answer[j]*=temp; } return answer; } }
|

345. 反转字符串中的元音字母
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public String reverseVowels(String s) { int len = s.length(); char[] arr = s.toCharArray(); int i=0; int j=len-1; while(i<j) { while(i<len && !isyuan(arr[i])) i++; while(!isyuan(arr[j])&&j>0) j--; if(i<j){ char t = arr[i]; arr[i]=arr[j]; arr[j]=t; i++; j--; } } return new String(arr);
} public boolean isyuan(char c){ return "aeiouAEIOU".indexOf(c)>=0; } }
|
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 26 27 28 29 30 31 32 33
| class Solution { public int compress(char[] chars) { int len = chars.length; StringBuilder sb = new StringBuilder(); for(int i=0;i<len;i++){ char temp = chars[i]; int j=i+1; int count=0; while(j<len){ if(temp==chars[j]) { j++; count++; } else { break; } } sb.append(temp); if(count<10&&count!=1) sb.append((char)count); else{ int t=0; String strcount = count+""; while(t<strcount.length()){ sb.append(strcount.charAt(t)); t++; } } } return sb.length(); } }
|