最长回文串:https://leetcode-cn.com/problems/longest-palindrome/
class Solution { public int longestPalindrome(String s) { //先用HashMap统计字符的出现次数 Map<Character,Integer> map = new HashMap<>(); char[] str = s.toCharArray(); for(char c : str){ if(map.containsKey(c)){ map.put(c,map.get(c)+1); }else{ map.put(c,1); } } int result = 0; //再遍历keySet出现次数,如果是奇数次,-1放在两边,如果是偶数次,直接放在两边 for(Character c : map.keySet()){ Integer time = map.get(c); if(time%2 == 0){ result += time; }else{ result += time-1; } } //如果长度比原字符串的长度短,+1,加上放置在中间的减掉的字符 if(result < s.length()){ //加上放置在中间的一个字符 return result+1; }else{ return result; } } }
最长回文子串:https://leetcode-cn.com/problems/longest-palindromic-substring/
class Solution { public String longestPalindrome(String s) { //回文子串问题,使用双指针中心拓展 String result = ""; //回文长度:2*len-1 for(int i=0;i<s.length()*2-1;i++){ //双指针 int left = i/2; int right = left + i%2; //双指针还未越界并且左右字符相同 while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){ //截取字符串,长度进行比较 String temp = s.substring(left,right+1); if(temp.length() > result.length()){ result = temp; } //拓展 left--; right++; } //拓展 left--; right++; } return result; } }
回文子串:https://leetcode-cn.com/problems/palindromic-substrings/
class Solution { public int countSubstrings(String s) { //回文子串,使用双指针中心拓展 int result = 0; for(int i=0;i<s.length()*2-1;i++){ int left = i/2; int right = left + i%2; //符合条件,result++ while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){ result++; left--; right++; } left--; right++; } return result; } }
字符串同构:https://leetcode-cn.com/problems/isomorphic-strings/
class Solution { public boolean isIsomorphic(String s, String t) { //长度不相同直接false if(s.length() != t.length()){ return false; } //使用HashMap,kv映射,s的字符对应t的字符 Map<Character,Character> map = new HashMap<>(); char[] s1 = s.toCharArray(); char[] t1 = t.toCharArray(); for(int i=0;i<s1.length;i++){ //map有s1[i],如果map.get(s1[i])不等于t1[i],说明不对应 if(map.containsKey(s1[i])){ if(map.get(s1[i]) != t1[i]){ return false; } }else{ //如果map中没有s1[i],但是有t1[i],说明不对应 if(map.containsValue(t1[i])){ return false; } } map.put(s1[i],t1[i]); } return true; } }
字符串压缩:https://leetcode-cn.com/problems/compress-string-lcci/
最长公共前缀:https://leetcode-cn.com/problems/longest-common-prefix/submissions/
class Solution { public String longestCommonPrefix(String[] strs) { if(strs.length == 0){ return ""; } //提取第一个字符串进行匹配 String result = strs[0]; for(int i=1;i<strs.length;i++){ //提取当前字符串 String temp = strs[i]; int j=0; //匹配temp for(;j<temp.length() && j<result.length();j++){ //不相同就break if(result.charAt(j) != temp.charAt(j)){ break; } } //截取从0到j的字符串 result = result.substring(0,j); } return result; } }