字符串算法

2020-06-02  本文已影响0人  万福来

最长公共前缀

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length == 0)
            return "";
        Arrays.sort(strs);
        char [] first = strs[0].toCharArray();
        char [] last = strs[strs.length - 1].toCharArray();
        StringBuffer res = new StringBuffer();
        int len = first.length < last.length ? first.length : last.length;
        int i = 0;
        while(i < len){
            if(first[i] == last[i]){
                res.append(first[i]);
                i++;
            }
            else
                break;
        }
        return res.toString();
    }
}

最长回文串

class Solution {
    //最长回文串
    public int longestPalindrome(String s) {
        HashSet<Character> hs = new HashSet<>();
        int len = s.length();
        int count = 0;
        if(len == 0)
            return 0;
        for(int i = 0; i<len; i++){
            if(hs.contains(s.charAt(i))){
                hs.remove(s.charAt(i));
                count++;
            }else{
                hs.add(s.charAt(i));
            }
        }
        return hs.isEmpty() ? count * 2 : count * 2 + 1;
    }
}

最长回文子序列

class Solution {
    //最长回文子序列
    public int longestPalindromeSubseq(String s) {
        int len = s.length();
        int [][] dp = new int[len][len];
        for(int i = len - 1; i>=0; i--){
            dp[i][i] = 1;
            for(int j = i+1; j < len; j++){
                if(s.charAt(i) == s.charAt(j))
                    dp[i][j] = dp[i+1][j-1] + 2;
                else
                    dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]);
            }
        }
        return dp[0][len-1];
    }
}

最长公共子串

func SerachMaxCommString(arr1 ,arr2 []int) []int {
    len1 := len(arr1)
    len2 := len(arr2)
    //利用二维数组记录子问题的LCS长度
    opt := make([][]int,len1,len1)
    for i := 0; i < len1; i++ {
        opt[i] = make([]int, len2)
    }
    for i:=0;i<len1;i++{
        for j:=0;j<len2;j++{
            if arr1[i] == arr2[j] {
                if i == 0 || j == 0 {
                    opt[i][j] = 1
                }else {
                    opt[i][j] = opt[i-1][j-1] + 1
                }
            }else{
                opt[i][j] = 0
            }
        }
    }
    //找出最大公共长度和坐标
    max := opt[0][0]
    indexi := 0
    indexj := 0
    for i:=0;i<len1;i++{
        for j:=0;j<len2;j++{
            if opt[i][j] > max {
                max = opt[i][j]
                indexi = i
                indexj = j
            }
        }
    }
    fmt.Printf("max lcs = %v \n",max)
    fmt.Printf("max lcs indexi= %v \n",indexi)
    fmt.Printf("max lcs indexj = %v \n",indexj)
    //取短的串返回
    narr := make([]int,max)
    index := 0
    var shortArr []int
    if len1 < len2 {
        index = indexi
        shortArr = arr1
    }else {
        index = indexj
        shortArr = arr2
    }
    fmt.Println(index)
    fmt.Println(shortArr)
    for i:=0;i<max;i++{
        fmt.Println(shortArr[index-max+1+i])
        narr[i] = shortArr[index-max+1+i]
    }
    return narr
}

反转单词顺序列

public String reverseWords(String s) {
        if(s.trim().length() == 0)
            return s.trim();
        String [] temp = s.trim().split(" +");
        String res = "";
        for(int i = temp.length - 1; i > 0; i--){
            res += temp[i] + " ";
        }
        return res + temp[0];
    }

反转字符串

public String reverseString(String s) {
        if(s.length() < 2)
            return s;
        int l = 0, r = s.length() - 1;
        char [] strs = s.toCharArray(); 
        while(l < r){
            char temp = strs[l];
            strs[l] = strs[r];
            strs[r] = temp;
            l++;
            r--;
        }
        return new String(strs);
    }

字符串转数字

public class Solution {
    public int StrToInt(String str) {
        if(str.length() == 0)
            return 0;
        int flag = 0;
        if(str.charAt(0) == '+')
            flag = 1;
        else if(str.charAt(0) == '-')
            flag = 2;
        int start = flag > 0 ? 1 : 0;
        long res = 0;
        while(start < str.length()){
            if(str.charAt(start) > '9' || str.charAt(start) < '0')
                return 0;
            res = res * 10 + (str.charAt(start) - '0');
            start ++;
        }
        return flag == 2 ? -(int)res : (int)res;
    }
}

IP-int互转

func IpToInt(ip string) (int32, error) {
    ipArr := strings.Split(ip, ".")
    if len(ipArr) != 4 {
        return 0, errors.New("IP is wrong")
    }
    ip1, err1 := strconv.Atoi(ipArr[0])
    ip2, err2 := strconv.Atoi(ipArr[1])
    ip3, err3 := strconv.Atoi(ipArr[2])
    ip4, err4 := strconv.Atoi(ipArr[3])
    if err1 != nil || err2 != nil || err3 != nil || err4 != nil {
        log.Println(err1, err2, err3, err4)
        return 0, errors.New("toint error")
    }
    ipInt := ip1<<24 + ip2<<16 + ip3<<8 + ip4
    return int32(ipInt), nil
}
func IntToIp(ip int32) string {
    ip1 := ip >> 24 & 0xFF
    ip2 := ip >> 16 & 0xFF
    ip3 := ip >> 8 & 0xFF
    ip4 := ip & 0xFF
    ips := fmt.Sprintf("%d.%d.%d.%d", ip1, ip2, ip3, ip4)
    return ips
}
上一篇下一篇

猜你喜欢

热点阅读