一些基本的算法研究

240 阅读1分钟

1、查找输入整数二进制中1的个数

方法一: 低位清零法

// 查找输入整数二进制中1的个数
public static int findNumberOf1(int number){
    int count =0;
    while (number!= 0){
        number &= number -1;
        count++;
    }
    return count;
}

方法二:使用Java的二进制转化算法

public static int findNumberOf1_Method2(int number){
    int count =0;
    String s = Integer.toBinaryString(number);
    for(int i=0;i<s.length();i++){
        if(s.charAt(i) == '1'){
            count++;
        }
    }
    return count;
}

2. DNA序列

题目:

/**
 * 题目描述
 * 一个DNA序列由A/C/G/T四个字母的排列组合组成。G和C的比例(定义为GC-Ratio)是序列中G和C两个字母的总的出现次数除以总的字母数目(也就是序列长度)。在基因工程中,这个比例非常重要。因为高的GC-Ratio可能是基因的起始点。
 * 给定一个很长的DNA序列,以及要求的最小子序列长度,研究人员经常会需要在其中找出GC-Ratio最高的子序列。
 *
 * 输入描述:  输入一个string型基因序列,和int型子串的长度
 *
 * 输出描述:  找出GC比例最高的子串,如果有多个输出第一个的子串
 *
 * 案例
 * 输入:
 * AACTGTGCACGACCTGA
 * 5
 * 输出:GCACG
 *
 */
public static String findSubString(String str,int l){
    int max = 0;
    int index = 0;
    for(int i=0;i<str.length() - l;i++){
        int temp =0;
        for(int j=0;j<l;j++){
            if (str.charAt(i+j) == 'G' || str.charAt(i+j) == 'C'){
                temp++;
            }
        }

        if (temp > max){
            max = temp;
            index = i;
        }
    }

    return str.substring(index,index+l);
}

3. 查找两个字符串a,b中的最长公共子串

/**
 * 题目描述
 * 查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。
 * 输入描述: 输入两个字符串
 *
 * 输出描述: 返回重复出现的字符
 *
 * 案例
 * 输入:
 * abcdefghijklmnop
 * abcsafjklmnopqrstuvw
 *
 * 输出:
 * jklmnop
 */
public static String findLongestStrBetweenTwoString(String s1,String s2){
    String str = null;
    int len = 0;
    for(int i=0;i<s2.length();i++){
        for(int j=i+len;j<s2.length();j++){
            if(s1.contains(s2.substring(i,j+1))){
                len=j-i+1;
                str = s2.substring(i, j + 1);
            }else {
                break;
            }
        }
    }

    return str;
}

24点游戏算法

/**
 *题目描述:
 * 问题描述:给出4个1-10的数字,通过加减乘除,得到数字为24就算胜利
 * 输入: 4个1-10的数字。[数字允许重复,但每个数字仅允许使用一次,测试用例保证无异常数字]
 * 输出: true or false
 * 输入描述: 输入4个int整数
 * 输出描述: 返回能否得到24点,能输出true,不能输出false
 *
 * 案例:
 * 输入:
 * 7 2 1 10
 * 输出:
 * true
 *
 */
public static boolean getResult(List<Integer> list, int temp){

    if(list.size() > 0){
        for(int i=0;i<list.size();i++){
            int n = list.get(i);
            list.remove(i);
            if(getResult(list,n*temp) || getResult(list,temp+n)|| getResult(list,temp-n)){
                return true;
            }else if(temp%n==0){
                if(getResult(list,temp/n)){
                    return true;
                }
            }
            list.add(i,n);
        }

        return false;
    }
    
    return  temp == 24;

}