200-300
263. 丑数
(https://leetcode-cn.com/problems/ugly-number/)
class Solution {
public boolean isUgly(int n) {
if(n < 1) return false;
while(n % 5 == 0){
n /= 5;
}
while(n % 3 == 0){
n /= 3;
}
while(n % 2 == 0){
n /= 2;
}
return (n == 1);
}
}
300-400
345. 反转字符串中的元音字母
(https://leetcode-cn.com/problems/reverse-vowels-of-a-string/)
class Solution {
public String reverseVowels(String s) {
int length = s.length();
char[] arr = new char[length]; // 返回数组
Character[] num = new Character[length]; // 记录元音字符的数组
int j = length-1;
int k =0; // 元音数组索引
while(j >= 0 ){
char c = s.charAt(j--);
// 遍历s,添加元音字符
if(c == 'a'|| c == 'e' || c == 'i' || c == 'o' || c == 'u'
|| c=='A'||c=='E'||c=='I'||c=='O'||c=='U' ){
num[k] = c;
k++;
}
}
int i = 0;
k = 0; // 从0开始遍历
while(i < length){
char c = s.charAt(i); // 如果是元音字母,就替换
if(c == 'a'|| c == 'e' || c == 'i' || c == 'o' || c == 'u'
|| c=='A'||c=='E'||c=='I'||c=='O'||c=='U'){
arr[i++] = num[k++];
}
else arr[i++] = c; // 否则不改变字母位置
}
return new String(arr);
}
}
383、赎金信
(https://leetcode-cn.com/problems/ransom-note/)
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
// 由于每个字符只能使用一次,所以可以使用hashMap来进行存储
// 将magazin里面的每个字符进行存储,再将ransoNote中的字符一一对比
Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i < magazine.length(); i++){
if(!map.containsKey(magazine.charAt(i))){
map.put(magazine.charAt(i), 1);
}else {
int value = map.get(magazine.charAt(i));
map.put(magazine.charAt(i), value+1); // 字符计数加一
}
}
for(int j = 0 ;j < ransomNote.length(); j++){
if(map.containsKey(ransomNote.charAt(j))){
int value = map.get(ransomNote.charAt(j));
if(value > 0){
map.put(ransomNote.charAt(j), value-1); // 字符计数减一
}else{
return false;
}
} else {
return false;
}
}
return true;
}
}
387、字符串中的第一个唯一字符
(https://leetcode-cn.com/problems/first-unique-character-in-a-string/)
// 方法一: 利用索引来做
class Solution {
public int firstUniqChar(String s) {
int first = 0;
int last = 0;
// 分别从前和从后查找该字符的位置,如果两个位置相同,则返回该位置索引
for (int i = 0; i < s.length(); i++){
first = s.indexOf(s.charAt(i));
last = s.lastIndexOf(s.charAt(i));
if(first == last){
return i;
}
}
return -1;
}
}
// 方法二: 利用hash来进行存储
389、找不同
(https://leetcode-cn.com/problems/find-the-difference/)
class Solution {
public char findTheDifference(String s, String t) {
int res = 0;
// 对每个字符进行异或出来,因为其他单词出现的次数都是偶数次,只有多添加的单词出现奇数次
for (char ch : s.toCharArray()){
res ^= ch;
}
for (char ch : t.toCharArray()){
res ^= ch;
}
return (char)res;
}
}
392、判断子序列
(https://leetcode-cn.com/problems/is-subsequence/)
class Solution {
public boolean isSubsequence(String s, String t) {
int i = 0;
int j = 0;
// 依次进行匹配
while (i < t.length() && j < s.length()){
char c = s.charAt(j);
if(t.charAt(i) == c){ // 每匹配到一个字符就往下走一位
j++;
}
i++;
}
if(j == s.length()) { // s遍历完,则匹配成功
return true;
}
else return false;
}
}