125. 验证回文串
import java.util.regex.*;
class Solution {
public boolean isPalindrome(String s) {
s = s.replaceAll("[^a-zA-Z0-9]","");
char [] str = s.toCharArray();
int i = 0;
int j = str.length - 1;
while(i < j)
/*
分享个字母大小写转换的方法:
统一转成大写:ch & 0b11011111 简写:ch & 0xDF
统一转成小写:ch | 0b00100000 简写:ch | 0x20
比较的时候注意加上小括号哦,因为位运算优先级比较低。
*/
if (((str[i++] & 0xDF) != (str[j--] & 0xDF)))
return false;
return true;
}
}
48. 最长不含重复字符的子字符串
import java.util.*;
class Solution {
public int lengthOfLongestSubstring(String s) {
int res = 0;
Set<Character> set = new HashSet<>();
for(int l = 0, r = 0; r < s.length(); r++){
while(set.contains(s.charAt(r)))
set.remove(s.charAt(l++));
set.add(s.charAt(r));
res = Math.max(res,r-l+1);
}
return res;
}
}
242.有效的字母异位词
方法一(排序):
import java.util.*;
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length())
return false;
char [] a = s.toCharArray();
char [] b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
return Arrays.equals(a,b);
}
}
方法二(哈希表):
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length())
return false;
int [] cnt = new int[26];
for(int i = 0; i < s.length(); i++){
cnt[s.charAt(i)-'a']++;
cnt[t.charAt(i)-'a']--;
}
for(int j : cnt)
if(j!=0)
return false;
return true;
}
}
409.最长回文串
- 做过前天那题的同学,很容易想到做一个int[26+26]数组来保存各字母的个数,但A~Z和a~z在ASCI I表上是分开的喔,所以存数组的时候也要分开存哦;
- 如果某字母有偶数个,因为偶数有对称性,可以把它全部用来构造回文串;
- 但如果是奇数个的话,并不是完全不可以用来构建,也不是只能选最长的那个,而是只要砍掉1个,剩下的变成偶数就可以全部计入了;
- 但奇数字母里,可以保留1个不砍,把它作为回文串的中心,所以最后还要再加回一个1 但是!如果压根没有奇数的情况,这个1也不能随便加,所以还要分情况讨论。
class Solution {
public int longestPalindrome(String s) {
int [] c = new int [26+26];
for(char ss : s.toCharArray()){
if(ss >= 'a'){
c[ss-'a']++;
}else{
c[ss-'A'+26]++;
}
}
int res = 0;
int odd = 0;
for(int cc : c){
res += cc;
if(cc%2==1){
odd++;
}
}
return odd==0?res:res-odd+1;
}
}
344.反转字符串
class Solution {
public void reverseString(char[] s) {
int l = 0;
int r = s.length - 1;
while(l < r){
swap(s,l,r);
l ++;
r --;
}
}
private void swap(char [] s, int i, int j){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
976.三角形的最大周长
class Solution {
public int largestPerimeter(int[] A) {
Arrays.sort(A);
for (int i = A.length - 3; i >= 0; --i)
if (A[i] + A[i+1] > A[i+2])
return A[i] + A[i+1] + A[i+2];
return 0;
}
}
寻找字符串中出现次数最多的字符,如果用多个出现最多的字符,则返回第一个
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static char find(String s){
Map<Character,Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
}
}
int count = 0;
Character temp = null;
for(Map.Entry<Character,Integer> entry: map.entrySet()){
if(entry.getValue() > count){
count = entry.getValue();
temp = entry.getKey();
}
}
return temp;
}
public static void main(String[] args) {
String str1 = "aaaccccdddd";
String str2 = "aaaccccdd";
System.out.println(find(str1)); //输出c
System.out.println(find(str2)); //输出c
}
}