4. 两个字符串包含的字符是否完全相同
242. Valid Anagram (Easy)
可以用 HashMap 来映射字符与出现次数,然后比较两个字符串出现的字符数量是否相同。
由于本题的字符串只包含 26 个小写字符,因此可以使用长度为 26 的整型数组对字符串出现的字符进行统计,不再使用 HashMap。
class Solution {
public boolean isAnagram(String s, String t) {
int[] hashchar=new int[26];
for(Character c:s.toCharArray()){
hashchar[c-'a']++;
}
for(Character c:t.toCharArray()){
hashchar[c-'a']--;
}
for(int num:hashchar){
if(num!=0){
return false;
}
}
return true;
}
}
5. 计算一组字符集合可以组成的回文字符串的最大长度
409. Longest Palindrome (Easy)
class Solution {
public int longestPalindrome(String s) {
char[] arr=s.toCharArray();
int[] cur=new int[52];
for(Character c:arr){
if(c>='A'&&c<='Z')cur[c-'A'+26]++;
else if(c>='a'&&c<='z')cur[c-'a']++;
}
int max=0;
int count=0;
for(int num:cur){
if(num==0)continue;
else if(num%2==0)count+=num;
else if(num%2==1)max=Math.max(max,num);
}
return count+max;
}
}
6. 字符串同构
205. Isomorphic Strings (Easy)
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
核心是记录字符串的索引
记录一个字符上次出现的位置,如果两个字符串中的字符上次出现的位置一样,那么就属于同构。
class Solution {
public boolean isIsomorphic(String s, String t) {
int[] arr_s=new int[256];
int[] arr_t=new int[256];
for(int i=0;i<s.length();i++){
char sc=s.charAt(i);
char tc=t.charAt(i);
if(arr_s[sc]!=arr_t[tc]){
return false;
}
arr_s[sc]=i+1;
arr_t[tc]=i+1;
}
return true;
}
}
7. 回文子字符串个数
647. Palindromic Substrings (Medium)
class Solution {
private int cnt=0;
public int countSubstrings(String s) {
for(int i=0;i<s.length();i++){
extendSubstring(s,i,i);//奇数判断
extendSubstring(s,i,i+1);//偶数判断
}
return cnt;
}
private void extendSubstring(String s,int start ,int end){
while(start>=0&&end<s.length()&&s.charAt(start)==s.charAt(end)){
start--;
end++;
cnt++;
}
}
}
8. 判断一个整数是否是回文数
9. Palindrome Number (Easy)
要求不能使用额外空间,也就不能将整数转换为字符串进行判断。
将整数分成左右两部分,右边那部分需要转置,然后判断这两部分是否相等。
简单
class Solution {
public boolean isPalindrome(int x) {
if(x==0)return true;
if(x<0||x%10==0)return false;
int reverse=0;
while(x>reverse){
reverse=reverse*10+x%10;
x/=10;
}
return x==reverse||x==reverse/10;
}
}
9. 统计二进制字符串中连续 1 和连续 0 数量相同的子字符串个数
696. Count Binary Substrings (Easy)
class Solution {
public int countBinarySubstrings(String s) {
int prelen=0,curlen=1,count=0;
for(int i=1;i<s.length();i++){
if(s.charAt(i)==s.charAt(i-1)){
curlen++;
}else{
prelen=curlen;
curlen=1;
}
if(prelen>=curlen){
count++;
}
}
return count;
}
}