牛客华为题库刷题笔记

split分隔符总结

\ split("\\\\")
. split("\\.")
/ split("\\/")
- split("\\-")
- split("\\s")

hasNext与hasNextLine

1、hasNext()方法会判断接下来是否有非空字符.如果有,则返回true,否则返回false
2、hasNextLine() 方法会根据行匹配模式去判断接下来是否有一行(包括空行),如果有,则返回true,否则返回false

如果在for循环的中途用完了一行,就会引发异常。

HJ1 字符串最后一个单词的长度

 import java.util.*;
public class Main{
    public static int lengthOfLast(String str) {
        String[] s =str.split(" ");
        return s[s.length-1].length();
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
            String str = scan.nextLine();
            System.out.println(lengthOfLast(str));
        }
    }
}

HJ2 计算某字符出现次数

import java.util.*;
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner s=new Scanner(System.in);
        String all="";
        String one="";
        char[] ac;
        char temp;
        int num=0;
        while(s.hasNext())
        {
            //s.toUpperCase(),String 转化为大写
            //s.toLowerCase(),String 转化为小写
            //String字符转换,s.toCharArray()与s.charAt(index)
            //char字符转换,String.valueOf(c)转化为String
        	all=s.nextLine();
            one=s.nextLine();
            //存放原来所有的
            ac=all.toCharArray();
            //存放要的字符
            //temp=one.charAt(0);
            for(int i=0;i<ac.length;i++)
            {
            	if(one.equalsIgnoreCase(String.valueOf(ac[i])))    
                    num++;
            }
            System.out.println(num);
        }
        
    }
    
}

HJ3 明明的随机数

import java.util.Scanner;
import java.util.TreeSet;
import java.util.Arrays;
 
public class Main
{
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        while(scan.hasNext()){
            int n = scan.nextInt();
            int[] array = new int[n];
            for(int i=0;i<n;i++){
                array[i] = scan.nextInt();
            }
            Arrays.sort(array);//对输入的数组进行排序
            //对排好序的数组中重复的数组进行选择输出,首先输出第一个数
            System.out.println(array[0]);
            for(int i=1;i<n;i++){
                if(array[i] != array[i-1])
                    System.out.println(array[i]);
            }
        }
    }
}

HJ4 字符串分隔

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){         
        	String s = new String(sc.nextLine());
        	if(s.length()%8 !=0 )
        		s = s + "00000000";
        	
        	while(s.length()>=8){
        		System.out.println(s.substring(0, 8));
        		s = s.substring(8);
        	}
        }
    }
}

HJ5 进制转换

import java.util.Scanner;
public class Main{
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        while(in.hasNextLine()){
            String str = in.nextLine();
            System.out.println(Integer.parseInt(str.substring(2),16));//str.substring(2)表示去除0x
        }
    }
}

HJ6 质数因子

好多人没明白这个问题的意思,其实就是让你把输入的整数因式分解,只不过因子必须都是质数
例如:180 = 2 * 2 * 3 * 3 * 590 = 2 * 3 * 3 * 5;而不是找出所有的质数因子

import java.util.Scanner;

public class Main
{
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		
		long number = 0;
		
		while(scanner.hasNextLong())
		{
			number = scanner.nextLong();
			isPrimerFactors(number);
		}
		
	}
	
	private static void isPrimerFactors(long num)
	{
		long number = num;
		while(number != 1)
		{
			for(int i = 2; i <= number ;i++)
			{
				if(number % i == 0)
				{
					number /= i;
					System.out.print(i + " ");
					break;
				}
			}
		}
	}
}


HJ7 取近似值

import java.util.ArrayList;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
        	double d = scan.nextDouble();
        	int dint = (int)d;
        	if((d-dint)>=0.5 && (d-dint)<1)
        		dint++;
        	System.out.println(dint);
        }
    }
}

HJ8 合并表记录

或者:需要将map.keySet转化为array,再通过Arrays.sort(array)进行排序,然后打印出来。

一般用StringBuffer做字符串反转reverse()

import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
			int n = sc.nextInt();
			for (int i = 0; i < n; i++) {
				int s=sc.nextInt();
				int value=sc.nextInt();
				if (map.containsKey(s)) {
					map.put(s, map.get(s) + value);
				} else
					map.put(s, value);
			}
			for (Integer key : map.keySet()) {
				System.out.println(key + " " + map.get(key));
			}
		}
	}
}

HJ9 提取不重复的整数

import java.util.*;

public class Main{
     public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        StringBuffer sb = new StringBuffer(str);
        Set s = new HashSet();
        sb.reverse();//字符串反转
        for(int i = 0;i<sb.length();i++){
           if(s.add(sb.substring(i,i+1))){//set不允许重复添加相同的元素
        	   System.out.print(sb.substring(i,i+1));
           }
        }
    }
}

HJ10 字符个数统计

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            String str=sc.nextLine();
            char[] ch=str.toCharArray();
            HashSet<Character> set=new HashSet<Character>();
            for (int i = 0; i < ch.length; i++) {
                set.add(ch[i]);
            }
            System.out.println(set.size());
        }
        sc.close();
    }
}

HJ11 数字颠倒

import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        StringBuffer sb = new StringBuffer(str);
        sb.reverse();
        System.out.println(sb.toString());
    }

}
import java.util.*;
public class Main{
	public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int i=0;
        String res="";
        
        while(num!=0){
        	int t1=num%10;
        	int t2=num/10;
        	res=res+String.valueOf(t1);
        	i++;
        	num=t2;	
        }
        System.out.println(res);
    }
}

HJ12 字符串反转

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            String s=sc.nextLine();
            for(int i=s.length()-1;i>=0;i--){
                System.out.print(s.charAt(i));
            }
        }
    }
}

HJ13 句子逆序

import java.util.Scanner;

/**
 * i am a boy=>boy a am i
 * @author Administrator
 *
 */
public class Main14 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			String str = sc.nextLine();
			int len = str.length();
			String[] s=str.split(" ");
			StringBuilder sb = new StringBuilder();
			for (int i = s.length-1; i >=0; i--) {
				sb.append(s[i]+" ");
			}
			
			System.out.println(sb.substring(0, len));
	}
	}
}

HJ14 字符串排序

import java.util.Arrays;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		String [] ss = new String[num];
		for (int i = 0; i < num; i++) {
			ss[i]=sc.next();
		}
		Arrays.sort(ss);
		for (int i = 0; i < ss.length; i++) {
			System.out.println(ss[i]);
		}
	}
}

为什么第9行 ss[i]=sc.nextLine()这样不行!显示老少一行…
因为int num = sc.nextInt()仅仅是把第一行的整数值读取了,在管道缓存中,还有换行符(enter),当在下面的nextLine()首先是读取第一行的换行符前面的数据,就是null,所以读取的数据就会少一行
这位同学解释的很好,但是nextLine()读取换行符前面的数据不包含换行符,不是null,而是空字符串,空字符串和null完全不一样

HJ15 求int型正整数在内存中存储时1的个数

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int count = 0;
        while(n>0){
            if((n&1)>0){
                count++;
            }
            n=n>>1;
        }
        System.out.println(count);
    }
}

HJ16 购物单

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 总钱数
        int N = scanner.nextInt();
        // 购买物品个数
        int m = scanner.nextInt();
        int[] f = new int[N + 1];
        // 分组,goods[i][0]为主件,goods[i][1]为附件1,goods[i][2]为附件2
        Good[][] goods1= new Good[60][4];

        for (int i = 1; i <= m; i++) {
            int v = scanner.nextInt();
            int p = scanner.nextInt();
            int q = scanner.nextInt();

            Good t = new Good(v, v * p);
            if (q == 0) {
                goods1[i][0] = t;
            } else {
                if (goods1[q][1] == null) {
                    goods1[q][1] = t;
                } else {
                    goods1[q][2] = t;
                }
            }
        }

        for (int i = 1; i <= m; i++) {
            for (int j = N; j >= 0 && goods1[i][0] != null; j--) {
                //以下代码从分组中选择价值最大的。共五种情况:不选主件,选主件,选附件1和主件,选附件2和主件,选附件1和附件2和主件
                Good master = goods1[i][0];
                int max = f[j];
                if (j >= master.v && max < f[j - master.v] + master.vp) {
                    max = f[j - master.v] + master.vp;
                }
                int vt;
                if (goods1[i][1] != null) {
                    if (j >= (vt = master.v + goods1[i][1].v)
                            && max <  f[j - vt] + master.vp + goods1[i][1].vp) {
                        max = f[j - vt] + master.vp + goods1[i][1].vp;
                    }
                }
                if (goods1[i][2] != null) {
                    if (j >= (vt = master.v + goods1[i][2].v)
                            && max <  f[j - vt] + master.vp + goods1[i][2].vp) {
                        max = f[j - vt] + master.vp + goods1[i][2].vp;
                    }
                }
                if (goods1[i][2] != null) {
                    if (j >= (vt = master.v + goods1[i][1].v + goods1[i][2].v)
                            && max < f[j - vt] + master.vp + goods1[i][1].vp + goods1[i][2].vp) {
                        max = f[j - vt] + master.vp + goods1[i][1].vp + goods1[i][2].vp;
                    }
                }
                f[j] = max;
            }
        }

        System.out.println(f[N]);
    }
}

class Good {
    int v;
    int vp;
    public Good(int v, int vp) {
        this.v = v;
        this.vp = vp;
    }
}

HJ17 坐标移动

import java.util.*;
public class Main{
    
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            String str=sc.nextLine();
            String[] A=str.split(";");
            int x=0,y=0;
            for(String string:A){
                if(string.length() < 2 || string.length() > 3) {continue;}
                if(string.charAt(0)=='D' && string.substring(1).matches("[0-9]+"))
                    x+=Integer.parseInt(string.substring(1));
                
                if(string.charAt(0)=='W' && string.substring(1).matches("[0-9]+"))
                    y+=Integer.parseInt(string.substring(1));
                
                if(string.charAt(0)=='S' && string.substring(1).matches("[0-9]+"))
                    y-=Integer.parseInt(string.substring(1));
                
                if(string.charAt(0)=='A' && string.substring(1).matches("[0-9]+"))
                    x-=Integer.parseInt(string.substring(1));
              
            }
            System.out.println(x+","+y);
        }
        
        sc.close();
    }
    
  
}

HJ18 识别有效的IP地址和掩码并进行分类统计

pass

HJ19 简单错误记录

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Map<String, Integer> map = new LinkedHashMap<>();
        while (sc.hasNext()) {
            String str_in = sc.next();
            int lineNum = sc.nextInt();
            String[] str_arr = str_in.split("\\\\");
            String name = str_arr[str_arr.length - 1];
            if (name.length() > 16) {
                name = name.substring(name.length() - 16);
            }
            String key = name + " " + lineNum;
            map.put(key, map.getOrDefault(key, 0) + 1);
        }
        
        int cnt = 0;
        for (String key : map.keySet()) {
            cnt++;
            if (cnt > map.keySet().size() - 8) {
                System.out.println(key + " " + map.get(key));
            }
        }
    }
};

HJ20 密码验证合格程序

import java.util.*;
public class Main {
    // 1.长度超过8位
    public static boolean checkLength(String password){
        if (password==null || password.length()<=8)
            return false;
        return true;
    }
    // 2.包括大小写字母.数字.其它符号,以上四种至少三种
    public static boolean checkCharKinds(String password){
        int Digit=0 , lowercase=0,uppercase=0,others=0;
        char[] ch = password.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (ch[i]>='0'&&ch[i]<='9') {
                Digit=1;
                continue;
            }
            else if (ch[i]>='a'&&ch[i]<='z') {
                lowercase=1;
                continue;
            }
            else if (ch[i]>='A'&&ch[i]<='Z') {
                uppercase=1;
                continue;
            }else {
                others=1;
                continue;
            }
        }
        int total = Digit+lowercase+uppercase+others;
        return total>=3 ? true : false;
    }
    // 3.不能有相同长度超2的子串重复
    public static boolean checkCharRepeat(String password){
        for(int i=0 ;i<password.length()-2 ;i++){
            String substr1 =password.substring(i, i+3);
            if (password.substring(i+1).contains(substr1))
               return false;
        }
        return true;
    }
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        while (cin.hasNextLine()) {
            String psw = cin.nextLine();
            if (checkLength(psw)&&checkCharKinds(psw)&&checkCharRepeat(psw))
                System.out.println("OK");
            else
                System.out.println("NG");
        }
    }
}

HJ24 合唱队

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int num = in.nextInt();
            if(num<=2){
                System.out.println(0);
            }
            int[] members=new int[num];//存储每一个数据元素
            int[] left_queue=new int[num];//数据元素从左到右对应的最大递增子序列数
            int[] right_queue=new int[num];//数据元素从右到左对应的最大递增子序列数
            for(int i=0;i<num;i++){//初始化各个数组数据
                members[i]=in.nextInt();
                left_queue[i]=1;
                right_queue[i]=1;
            }
            for(int i=0;i<num;i++){
                for(int j=0;j<i;j++){
                    if(members[i]>members[j]&&left_queue[j]+1>left_queue[i])
                        left_queue[i]=left_queue[j]+1;
                }
            }
            for(int i=num-1;i>=0;i--){
                for(int j=num-1;j>i;j--){
                    if(members[i]>members[j]&&right_queue[j]+1>right_queue[i])
                        right_queue[i]=right_queue[j]+1;                   
                }
            }
            int max=0;
            for(int i=0;i<num;i++){
                if(left_queue[i]+right_queue[i]>max)
                    max=left_queue[i]+right_queue[i];
            }
            System.out.println(num-max+1);
        }
    }
}

HJ25 数据分类处理

import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.util.LinkedList;

public class Main{
   public static void resultData(String[] strR, String[] strI){
        LinkedList<Integer> result = new LinkedList<>();
        Set<Integer> setR = new TreeSet<>();
        for (int i = 1; i < strR.length; i++){
            setR.add(Integer.parseInt(strR[i]));
        } 

        for (int str : setR){
            LinkedList<Integer> tmp = new LinkedList<>();
            for (int i = 1; i < strI.length; i++){
                if (strI[i].contains("" + str)){
                    tmp.add(i - 1);
                    tmp.add(Integer.parseInt(strI[i]));
                }
            }
            if (!tmp.isEmpty()){
                result.add(str);
                result.add((tmp.size() / 2));
                result.addAll(tmp);
            }
        }
        
        System.out.print(result.size() + " ");
       int count = result.size();
        for (int ele : result){
            if (count != 1)
                System.out.print(ele + " ");
            else 
                System.out.print(ele);
            count--;
            
        }
       System.out.println();
       
    }
        
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()){
            String I = sc.nextLine();
            String R = sc.nextLine();
            String[] arrR = R.split(" ");
            String[] arrI = I.split(" ");
            resultData(arrR, arrI);
        }
        sc.close();
    }
}

HJ26 字符串排序

import java.util.*;
 
public class Main
{
    public static void main(String[] args)
    {
        Scanner sca = new Scanner(System.in);
        while (sca.hasNext())
        {
            String str = sca.nextLine();
            char [] cha = str.toCharArray();
            StringBuffer sb = new StringBuffer();
             
            for (int i = 0; i<26; i++)
            {
                char c = (char)(i + 'A');
                for (int j = 0; j<str.length(); j++)
                {
                    if (cha[j] == c || cha[j] == (char)(c + 32))
                    sb.append(cha[j]);
                }
            }
             
            for (int k = 0; k<str.length(); k++)
            {
                if (!(cha[k] >= 'A' && cha[k] <= 'Z' || cha[k] >= 'a' && cha[k] <= 'z'))
                sb.insert(k, cha[k]);
            }
            System.out.println(sb.toString());
        }
    }
         
}

HJ27 查找兄弟单词


import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;

public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while(in.hasNext()){
			int num = in.nextInt();
			String[] s = new String[num];
			int count = 0;
			for(int i = 0;i<num;i++){
				s[i] = in.next();
			}
			String key = in.next();
			char[] keyChar = key.toCharArray();
			Arrays.sort(keyChar);
			int no = in.nextInt();//第几个
			ArrayList<String> list = new ArrayList<String>();
			for(int i = 0;i<num;i++){
				int c = check(key,s[i],keyChar);
				count += c;
				if(c==1)
					list.add(s[i]);
			}
			System.out.println(count);
			Collections.sort(list);
			if(count>=no)
				System.out.println(list.get(no-1));
		}
	}
	private static int check(String key,String word,char[] keyChar){
		if(key.equals(word)||key.length()!=word.length())
			return 0;
		char[] wordChar = word.toCharArray();
		Arrays.sort(wordChar);
		return Arrays.equals(keyChar, wordChar)?1:0;
	}
}

HJ28 素数伴侣

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

vector<int> G[105];

bool flag[105];
int pre[105];

bool dfs(int k){
    int x;
    for(int i=0;i<G[k].size();i++){
        x=G[k][i];
        if (flag[x]) continue;
        flag[x]=true;
        if((pre[x]==0)||dfs(pre[x])){
            pre[x]=k;
            return true;
        }
    }
    return false;
}

bool isprime[80000];
int nums[105];

int main(){
    memset(isprime,1,sizeof(isprime));
    isprime[0]=isprime[1]=false;
    for(int i=4;i<80000;i+=2)isprime[i]=false;
    for(int i=3;i*i<80000;i+=2)
        if(isprime[i]){
            for(int j=i*i;j<80000;j+=2*i) isprime[j]=false;
        }
    int n;
    while(~scanf("%d",&n)){
        for(int i=1;i<=n;i++){
            scanf("%d",&nums[i]);
        }
        for(int i=1;i<=n;++i){
            for(int j=i+1;j<=n;++j){
                if(isprime[nums[i]+nums[j]]){
                    (nums[i]&1)?G[i].push_back(j):G[j].push_back(i);
                }
            }
        }

        memset(pre,0,sizeof(pre));
        int ans=0;
        for(int i=1;i<=n;i++){
            memset(flag,false,sizeof(flag));
            if (dfs(i)) ans++;
        }
        printf("%d\n",ans);
        
        for(int i=1;i<=n;++i){
            G[i].clear();
        }
    }
    return 0;
}

HJ29 字符串加解密

import java.util.*;

public class Main {
	
	public static char encryption(char c){
		if(c >= 'a' && c < 'z')
			return (char)(c + 1 - 32);
		else if(c == 'z')
			return 'A';
		else if(c >= 'A' && c < 'Z')
			return (char)(c + 1 + 32);
		else if(c == 'Z')
			return 'a';
		else if(c >= '0' && c < '9')
			return (char)(c + 1);
		else if(c == '9')
			return '0';
		else 
			return c;
	}
	
	public static char decryption(char c){
		if(c > 'a' && c <= 'z')
			return (char)(c - 1 - 32);
		else if(c == 'a')
			return 'Z';
		else if(c > 'A' && c <= 'Z')
			return (char)(c - 1 + 32);
		else if(c == 'A')
			return 'z';
		else if(c > '0' && c <= '9')
			return (char)(c - 1);
		else if(c == '0')
			return '9';
		else 
			return c;
	}
	
	public static String enCryption(String s){
		char[] cs = s.toCharArray();
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < cs.length; i++){
			sb.append(encryption(cs[i]));
		}
		return sb.toString();
	}
	
	public static String deCryption(String s){
		char[] cs = s.toCharArray();
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < cs.length; i++){
			sb.append(decryption(cs[i]));
		}
		return sb.toString();
	}
	
    public static void main(String args[]) {
    	Scanner sc = new Scanner(System.in);
    	while(sc.hasNext()){
    		String s1 = sc.nextLine();
    		String s2 = sc.nextLine();
    		System.out.println(enCryption(s1));
    		System.out.println(deCryption(s2));
    	}
    	sc.close();
    }
}

HJ30 字符串合并处理

牛客华为题库刷题笔记_第1张图片

//代码较多,但是思路比较清晰,一步步的来!
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.next();
            str += sc.next();
            System.out.println(processString(str));
        }
    }
    private static String processString(String str){
        if(str==null||str.length()==0){
            return "";
        }
        int n = str.length();
        ArrayList<Character> ji = new ArrayList<>();
        ArrayList<Character> ou = new ArrayList<>();
        for(int i=0;i<n;i++){//奇数和偶数分开存到集合中
            if(i%2==0){
                ou.add(str.charAt(i));
            }else{
                ji.add(str.charAt(i));
            }
        }
        //排序
        Collections.sort(ji);
        Collections.sort(ou);
        char[] chs = new char[n];
        int ouIndex = 0,jiIndex = 0;
        for(int i=0;i<n;i++){//之后再把排序后的奇数偶数重新放到char型数组中
            if(i%2==0){
                chs[i] = ou.get(ouIndex++);
            }else{
                chs[i] = ji.get(jiIndex++);
            }
        }
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<n;i++){//依次把char型数组中的字符经过处理后就加入到stringbuffer中
            char ch = chs[i];
            if((ch>='0'&&ch<='9')||(ch>='a'&&ch<='f')||(ch>='A'&&ch<='F')){
                sb.append(processChar(ch));
            }else{
                sb.append(ch);
            }
        }
        return sb.toString();
    }
    private static char processChar(char c){//处理这些特殊字符,返回char型字符
        int num = 0;//num代表该字符所代表的十六进制数字
        if(c>='0'&&c<='9'){
             num = Integer.parseInt(c+"");
        }else if(c>='a'&&c<='f'){
             num = c-87;
        }else {
             num = c-55;
        }
        return getReverseResult(num);//也就是对该十六进制数字进行处理
    }
    private static char getReverseResult(int num){//对该十六进制数字进行处理
        String nums = reverseBinaryString(num);//对该数字进行转化为4位二进制数,然后反转。
        int res = Integer.parseInt(nums,2);//之后再对返回后的二进制字符串转换为十进制数字
        if(res>=0&&res<=9){//对十进制数字分两种情况转换为十六进制字符
              return (res+"").charAt(0);
         }else{
              return (char)(res+55);
         }
    }
    //对该数字进行转化为4位二进制数,然后反转,返回反转后的字符串
    private static String reverseBinaryString(int num){
        int k = 1<<3;
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<4;i++){
            int flag = ((num&k)==0?0:1);
            sb.append(flag);
            num=num<<1;
        }
        return sb.reverse().toString();
    }
}

HJ32 密码截取

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.nextLine();
            System.out.println(process(str));
        }
    }
    public static int process(String str) {
        int n = str.length();
        int res = 0;
        for (int i = 0; i < n; i++) {
            res = Math.max(res, findLongest(i, i, str));
            res = Math.max(res, findLongest(i, i + 1, str));
        }
        return res;
    }
    public static int findLongest(int left, int right, String str) {
        while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }
}

HJ33 整数与IP地址间的转换

import java.util.*;
//遇到的问题,数组越界,输入格式不正确,应都为String输入;
//int型溢出,要换为long型
public class Main
{  
    public static void main(String[] args)
    {
         Scanner in=new Scanner(System.in);
         while(in.hasNext()){
        	String ip=in.nextLine();
        	String p=in.nextLine();
        	System.out.println(IptoTen(ip));
        	TentoIp(p);
        	
        }
    }
	private static void TentoIp(String p) {
		long temp=Long.parseLong(p);
		String ip=Long.toBinaryString(temp);
		StringBuilder sb=new StringBuilder();
		if(ip.length()<32){
			for(int i=0;i<(32-ip.length());i++){
				sb.append(0);
			}
			sb.append(ip);
		}else if(ip.length()==32){
			sb.append(ip);
		}
		for(int i=0;i<sb.length()-8;i=i+8){
			
			System.out.print(Integer.parseInt(sb.substring(i,i+8),2)+".");
		}
		System.out.println(Integer.parseInt(sb.substring(sb.length()-8,sb.length()),2));
		
	}
	private static long IptoTen(String ip) {
		String[] arr=ip.split("\\.");
		long n=Long.parseLong(arr[0]); //????
		
		for(int i=1;i<arr.length;i++){
			n=n<<8;
			n=n+Long.parseLong(arr[i]);
		}
		return n;
	}
}

HJ36 字符串加密

import java.util.*;

public class Main {
	
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		while (cin.hasNext()) {
			char[] key = cin.next().toCharArray(),
					s = cin.next().toCharArray();
			
			Set<Character> set = new HashSet<>();
			char[] table = new char[26];
			int k = 0;
			
			
			for (int i = 0; i < key.length; ++i) {
				char c = key[i];
				if (!set.contains(c)) {
					table[k++] = c;
					set.add(Character.toLowerCase(c));
				}
			}
			
			for (; k < 26; ++k) {
				for (int i = 0; i < 26; ++i) {
					char c = (char) ('a' + i);
					if (!set.contains(c)) {
						table[k++] = c;
						set.add(Character.toLowerCase(c));
					}
				}
			}
			
			for (int i = 0; i < s.length; ++i) {
				boolean up = false;
				char c = s[i];
				if (Character.isUpperCase(c)) {
					up = true;
				}
				
				char res = table[c - 'a'];
				if (up) {
					System.out.print(Character.toUpperCase(res));
				}
				System.out.print(res);
			}
			
			System.out.println();
		}
	}
}

HJ38 求小球落地5次后所经历的路程和第5次反弹的高度

import java.util.Scanner;

public class Main {     
    public static void main(String[] args) {         
        Scanner s = new Scanner(System.in);         
        while(s.hasNextDouble()) {             
            double n = s.nextDouble();             
            System.out.println(n/32*92);             
            System.out.println(n/32);         
        }     
    }
}

HJ39 判断两个IP是否属于同一子网

17/20 组用例通过

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String s = in.nextLine();
            String s1 = in.nextLine();
            String s2 = in.nextLine();
            if (s==null || s.length()==0 || s1==null || s1.length()==0 ||s2==null || s2.length()==0) {
				System.out.println(1);
				break;
			}
            boolean flag = false;
            String ss[] = s.split("\\.");
            String ss1[] = s1.split("\\.");
            String ss2[] = s2.split("\\."); 
            for(int i =0;i<ss.length;i++){
            	if(Integer.valueOf(ss[i])<0 || Integer.valueOf(ss[i])>255 || Integer.valueOf(ss1[i])<0 || Integer.valueOf(ss1[i])>255 || Integer.valueOf(ss2[i])<0 || Integer.valueOf(ss2[i])>255){
            		System.out.println(1);
            		System.exit(0);
            	}
            } 
            for(int i=0;i<ss.length;i++){
            	if ((Integer.valueOf(ss[i]) & Integer.valueOf(ss1[i])) == (Integer.valueOf(ss[i]) & Integer.valueOf(ss2[i]))) {
					flag = true;
				} else {
					flag = false;
					break;
				}
            }
            if (flag) {
				System.out.println(0);
			}else {
				System.out.println(2);
			}
        }
        
    }
    
}

HJ41 称砝码

//依次类推,得出n种砝码的情况
import java.util.*;

public class Main{
    public static int fama(int n, int[] weight, int[] nums){
        Set<Integer> set = new HashSet<Integer>();
        for(int i = 0; i <= nums[0]; i++){
            set.add(weight[0] * i);
        }
        for(int i = 1; i < n; i++){
            List<Integer> list = new ArrayList<Integer>(set);
            for(int j = 0; j <= nums[i]; j++){
                for(int k = 0; k < list.size(); k++){
                 set.add(list.get(k) + j * weight[i]);
                }
            }
        }
        return set.size();
    }
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            int n = in.nextInt();
            int[] weight = new int[n];
            int[] nums = new int[n];
            for(int i = 0; i < n; i++){
                weight[i] = in.nextInt();
            }
            for(int i = 0; i < n; i++){
                nums[i] = in.nextInt();
            }
            System.out.println(fama(n, weight, nums));
        }
        in.close();
    }
}

HJ42 学英语

import java.util.*;
public class Main {

	public static String[] num1 = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
	public static String[] num2 = { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen","seventeen", "eighteen", "nineteen" };
	public static String[] num3 = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty","ninety" };

	public static String parse(long num){
		if(num < 0){
			return "error";
		}
		StringBuilder sb = new StringBuilder();
		long billion = num / 1000000000;    //十亿部分
		if(billion != 0){
			sb.append(trans(billion) + " billion ");
		}
		num  %= 1000000000;
		
		long million = num / 1000000;    //百万部分
		if(million != 0){
			sb.append(trans(million) + " million ");
		}
		num  %= 1000000;
		
		long thousand = num / 1000;    //千部分
		if(thousand != 0){
			sb.append(trans(thousand) + " thousand ");
		}
		num  %= 1000;
	
		if(num != 0){
			sb.append(trans(num));
		}
		return sb.toString().trim();   //最后去除字符串后面的空格
	}

	public static String trans(long num){
		StringBuilder sb = new StringBuilder();
		long h  = num / 100;  //百位处理
		if(h != 0){
			sb.append(num1[(int) h] + " hundred");
		}
		num %= 100;
		
		long k = num / 10;    //十位处理
		if(k != 0){
			if(h != 0){    //若有百位,则加上“and”
				sb.append(" and ");
			}
			if(k == 1){   //如果十位为1,那么十位与个位一起翻译,如:113
				sb.append(num2[(int)(num % 10)]);
			}else{  //否则,十位和个位分别单独翻译,如:123
				sb.append(num3[(int) (k - 2)] + " ");
				if(num % 10 != 0){
					sb.append(num1[(int) (num % 10)]);
				}
			}
		}else if (num % 10 != 0) {  //如果没有十位的部分,则直接翻译个位部分,比如:102
			if(h != 0){
				sb.append(" and ");
			}
			sb.append(num1[(int) (num % 10 )]);
		}
		return sb.toString().trim();
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			long num = in.nextLong();
			System.out.println(parse(num));
		}
		in.close();
	}
}

HJ43 迷宫问题

20/26

import java.util.*;

public class Main {
	
    public static void main(String[] args) {
    	Scanner jin = new Scanner(System.in);
    	while(jin.hasNext()) {
    		int row = jin.nextInt();
    		int col = jin.nextInt();
    		int[][] maze = new int[row][col];
    		for(int i = 0; i < row; i++)
    			for(int j = 0; j < col; j++)
    				maze[i][j] = jin.nextInt();
    		check(maze, 0, 0);//预先探测迷宫一遍,将走不通的路置1
    		System.out.println(mazePath(maze, 0, 0));//正式走迷宫
    	}
    }
    public static int check(int[][] maze, int x, int y) {
        //如果是右下角的出口
    	if(x == maze.length - 1 && y == maze[x].length - 1) return 1;
        //如果当前位置是路
    	if(x < maze.length && y < maze[maze.length - 1].length && maze[x][y] == 0) {
                //如果下一步横竖都是死
    		if(check(maze, x + 1, y) == -1 && check(maze, x, y + 1) == -1) {
                        //将本位置封死
    			maze[x][y] = 1;
    			return -1;
    		}else return 1;
        //如果当前位置不是路
    	}else return -1;
    }
    public static String mazePath(int[][] maze, int x, int y) {
        //如果是右下角的出口,返回坐标
    	if(x == maze.length - 1 && y == maze[x].length - 1) return "(" + x + "," + y + ")";
        //如果当前位置是路,返回坐标并且继续前进
    	if(x < maze.length && y < maze[maze.length - 1].length && maze[x][y] == 0) return "(" + x + "," + y + ")" + "\n" + mazePath(maze, x + 1, y) + mazePath(maze, x, y + 1);
        //如果当前位置不是路,什么也不做
    	else return "";
    }
}

HJ44 Sudoku

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[][] matrix = new int[9][9];
        while (sc.hasNext()) {
            for (int i = 0; i < 9; i ++) {
                for (int j = 0; j < 9; j ++) {
                    matrix[i][j] = sc.nextInt();
                }
            }
            sudoku(matrix, 0, 0);
            for (int i = 0; i < 9; i ++) {
                for (int j = 0; j < 9; j ++) {
                    if(j == 8) System.out.println(matrix[i][j]);
                    else System.out.print(matrix[i][j] + " ");
                }
            }
        }
    }
    public static boolean sudoku(int[][] matrix, int i, int j) {
        if(i > 8) return true;
        if(matrix[i][j] != 0) {
            if(j < 8 && sudoku(matrix, i, j + 1)) return true; // 未到行位,求解同行下一个
            else if(j >= 8 && sudoku(matrix, i + 1, 0)) return true; // 已到行位,求解下一行第一个
        } else {
            for (int num = 1; num <= 9; num ++) {
                if(check(matrix, i, j, num)) {
                    matrix[i][j] = num;
                    if(j < 8 && sudoku(matrix, i, j + 1)) return true;
                    else if(j >= 8 && sudoku(matrix, i + 1, 0)) return true;
                    matrix[i][j] = 0; // 回溯
                }
            }
        }
        return false;
    }
    // 检查行、列、3*3格
    public static boolean check(int[][] matrix, int i, int j, int num) {
        if(check_row(matrix, i, j, num) && check_col(matrix, i, j, num) && check_3_by_3(matrix, i, j, num)) return true;
        return false;
    }
    // 检查所在行
    public static boolean check_row(int[][] matrix, int i, int j, int num) {
        for (int k = 0; k < 9; k ++) {
            if(matrix[i][k] == num) return false;
        }
        return true;
    }
    // 检查所在列
    public static boolean check_col(int[][] matrix, int i, int j, int num) {
        for (int k = 0; k < 9; k ++) {
            if(matrix[k][j] == num) return false;
        }
        return true;
    }
    // 检查所在3*3格
    public static boolean check_3_by_3(int[][] matrix, int i, int j, int num) {
        int row_from = i / 3 * 3;
        int row_to = row_from + 2;
        int col_from = j / 3 * 3;
        int col_to = col_from + 2;
        for (int x = row_from; x <= row_to; x ++) {
            for (int y = col_from; y <= col_to; y ++) {
                if(matrix[x][y] == num) return false;
            }
        }
        return true;
    }
}

HJ45 名字的漂亮度

import java.util.*;
 
public class Main{
    public static void main(String[] args){
 		Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
            int N = scan.nextInt();
            String[] str = new String[N];
            for(int i=0;i<N;i++){
                str[i] = scan.next();
            }

            for(int i=0;i<N;i++){
                int[] count = new int[26];
                int len = str[i].length();
                for(int j=0;j<len;j++){
                    int ascii = str[i].charAt(j);
                    //System.out.println("ascii="+ascii);
                    if(ascii>='a'&& ascii<='z'){
                        count[ascii-97]++;
                    }else if(ascii>='A'&& ascii<='Z'){
                        count[ascii-65]++;
                    }
                }
                Arrays.sort(count);
                int piaoliangdu = 0;
                for(int k =0;k<26;k++){
                    piaoliangdu+=count[k]*(k+1);
                }
                System.out.println(piaoliangdu);
            }
        }
        scan.close();
    }
}

HJ48 从单向链表中删除指定值的节点

import java.util.ArrayList;
import java.util.Scanner;
public class Main{
	public static void main(String[] args){  
		Scanner sc = new Scanner(System.in);
		while(sc.hasNextInt()){
			int num = sc.nextInt();
			int firstNode = sc.nextInt();
			ArrayList<Integer> list = new ArrayList<>();
			list.add(firstNode);
			for(int i=0;i<num-1;i++){
				int Node1 = sc.nextInt();			//要插入的节点
				int Node2 = sc.nextInt();			//插入在哪个节点之后
				int index = list.indexOf(Node2);
				list.add(index+1,Node1);

			}
			Object deleteNode = sc.nextInt();
			list.remove(deleteNode);
			for(int i=0;i<list.size()-1;i++){
				System.out.print(list.get(i)+" ");
			}
			System.out.println(list.get(list.size()-1)+" ");
		}
		sc.close();
	}
}

HJ50 四则运算

import java.util.*;
public class Main{
    // 用于存放一个正括号的集合, 用于简化代码
    static Set<Character> brace = new HashSet<>();
    public static void main(String ... args){
        Scanner sc = new Scanner(System.in);
        // 初始化正括号集合
        brace.add('{');
        brace.add('(');
        brace.add('[');
        while(sc.hasNextLine()){
            // 对字符串做初始化处理,原则有二:
            // 1、处理负数,这里在-前面的位置加入一个0,如-4变为0-4,
            // 细节:注意-开头的地方前面一定不能是数字或者反括号,如9-0,(3-4)-5,这里地方是不能加0的
            // 它的后面可以是数字或者正括号,如-9=>0-9, -(3*3)=>0-(3*3)
            // 2、处理字符串,在最后的位置加#, 主要是为了防止最后一个整数无法处理的问题
            String exp = sc.nextLine().replaceAll("(?, "0") + "#";
            System.out.println(calculate(exp));
        }
    }
    private static int calculate(String exp){
        // 初始化栈
        Stack<Integer> opStack = new Stack<>();
        Stack<Character> otStack = new Stack<>();
        
        // 整数记录器
        String num = "";
        for(int i = 0; i < exp.length(); i++){
            // 抽取字符
            char c = exp.charAt(i);
            // 如果字符是数字,则加这个数字累加到num后面
            if(Character.isDigit(c)){
                num += c;
            }
            // 如果不是数字
            else{
                // 如果有字符串被记录,则操作数入栈,并清空
                if(!num.isEmpty()){
                    int n = Integer.parseInt(num);
                    num = "";
                    opStack.push(n);
                }
                // 如果遇上了终结符则退出
                if(c == '#')
                    break;
                // 如果遇上了+-
                else if(c == '+' || c == '-'){
                    // 空栈或者操作符栈顶遇到正括号,则入栈
                    if(otStack.isEmpty() || brace.contains(otStack.peek())){
                        otStack.push(c);
                    } else {
                        // 否则一直做弹栈计算,直到空或者遇到正括号为止,最后入栈
                        while(!otStack.isEmpty() && !brace.contains(otStack.peek()))
                            popAndCal(opStack, otStack);
                        otStack.push(c);
                    }
                }
                // 如果遇上*/
                else if(c == '*' || c == '/'){
                    // 空栈或者遇到操作符栈顶是括号,或者遇到优先级低的运算符,则入栈
                    if(otStack.isEmpty()
                            || brace.contains(otStack.peek())
                            || otStack.peek() == '+' || otStack.peek() == '-'){
                        otStack.push(c);
                    }else{
                        // 否则遇到*或/则一直做弹栈计算,直到栈顶是优先级比自己低的符号,最后入栈
                        while(!otStack.isEmpty()
                                && otStack.peek() != '+' && otStack.peek() != '-'
                                && !brace.contains(otStack.peek()))
                            popAndCal(opStack, otStack);
                        otStack.push(c);
                    }
                } else {
                    // 如果是正括号就压栈
                    if(brace.contains(c))
                        otStack.push(c);
                    else{
                        // 反括号就一直做弹栈计算,直到遇到正括号为止
                        char r = getBrace(c);
                        while(otStack.peek() != r){
                            popAndCal(opStack, otStack);
                        }
                        // 最后弹出正括号
                        otStack.pop();
                    }
                }
            }
        }
        // 将剩下的计算完,直到运算符栈为空
        while(!otStack.isEmpty())
            popAndCal(opStack, otStack);
        // 返回结果
        return opStack.pop();
    }
    private static void popAndCal(Stack<Integer> opStack, Stack<Character> otStack){
        int op2 = opStack.pop();
        int op1 = opStack.pop();
        char ot = otStack.pop();
        int res = 0;
        switch(ot){
            case '+':
                res = op1 + op2;
                break;
            case '-':
                res = op1 - op2;
                break;
            case '*':
                res = op1 * op2;
                break;
            case '/':
                res = op1 / op2;
                break;
        }
        opStack.push(res);
    }
    private static char getBrace(char brace){
        switch(brace){
            case ')':
                return '(';
            case ']':
                return '[';
            case '}':
                return '{';
        }
        return '#';
    }
}

HJ52 计算字符串的编辑距离

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str1 = sc.nextLine();
            String str2 = sc.nextLine();
            int m = str1.length();
            int n = str2.length();
            int[][] dp = new int[m + 1][n + 1];
            for (int i = 0; i <= m; i++) 
                dp[i][0] = i;
            for (int j = 0; j <= n; j++) 
                dp[0][j] = j;
            for (int i = 1; i <= m; i++) {
                char ch1 = str1.charAt(i - 1);
                for (int j = 1; j <= n; j++) {
                    char ch2 = str2.charAt(j - 1);
                    if (ch1 == ch2) {
                        dp[i][j] = dp[i - 1][j - 1];
                    } else {
                        dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), 
                                            dp[i - 1][j - 1]) + 1;
                    }
                }
            }
            System.out.println(dp[m][n]);
        }
    }
}

HJ55 挑7

import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            int N = in.nextInt();
            int result = 0;
            if(N == 0) System.out.println(result);
            String str = new String();
            for(int i = 1; i <= N; i++){
                str = String.valueOf(i);
                if(str.contains("7") || i % 7 == 0){
                    result++;
                }
            }
            System.out.println(result);
        }
        in.close();
    }
}

HJ57 高精度整数加法

import java.math.BigInteger;
import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		while(in.hasNext()){
          String a=in.next();
		  String b=in.next();
		  BigInteger c=new BigInteger(a);
		  BigInteger d=new BigInteger(b);
		  System.out.println(c.add(d));
        }
	}
}

HJ59 找出字符串中第一个只出现一次的字符

import java.util.Scanner; 
   
public class Main {  
   
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in); 
        while(sc.hasNext()){
            String str = sc.nextLine();
            char[] cs = str.toCharArray();
            String s = "-1";
            for(int i = 0; i < cs.length; i++){
                if(str.indexOf(cs[i]) == str.lastIndexOf(cs[i])){
                    s = cs[i] + "";
                    break;
                }
            }
            System.out.println(s);
        }
        sc.close(); 
    } 
}

HJ63 DNA序列

import java.util.*;
public class Main {
		public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		while (input.hasNext()) {
			String str = input.next();
			int n = input.nextInt();
			int max = 0;
			int maxBeginIndex = 0;
			for (int i = 0; i <= str.length()-n; i++) {
				int count = 0;
				for (int j = i; j < i+n; j++) {
					if (str.charAt(j)=='G'||str.charAt(j)=='C')
						count++;
				}
				if (count > max){
					maxBeginIndex = i;
					max = count;
				}
			}
			System.out.println(str.substring(maxBeginIndex, maxBeginIndex+n));
		}
	}
}


HJ64 MP3光标位置

import java.util.*;

public class Main {
	public static void MP3PlayerLow4(String str, int n) {
			char[] ch = str.toCharArray();
			int begin = 1, cur = 1; // 起始序号,当前歌曲序号
			for (int i = 0; i < ch.length; i++) {
				if (cur == 1 && ch[i] == 'U') { // 光标在第一首歌曲上时,按Up键光标
					cur = n;
					continue;
				}
				if (cur == n && ch[i] == 'D') { // 光标在最后一首歌曲时,按Down键光标
					cur = 1;
					continue;
				}
				if (ch[i] == 'U') {
					cur -= 1;
				}
				if (ch[i] == 'D') {
					cur += 1;
				}
			}
			for (int i = 0; i < n; i++) {
				if (i==0) {
					System.out.print(begin);
				}else{
					System.out.print(" "+(begin+i));
				}
			}
			System.out.println();
			System.out.println(cur);
	}

	public static void MP3PlayerUp4(String str, int n) {
		char[] ch = str.toCharArray();
		int begin = 1, cur = 1; // 起始序号,当前歌曲序号
		for (int i = 0; i < ch.length; i++) {
			if (begin==1 && cur == 1 && ch[i] == 'U') { // 光标在第一页 ,第一首歌曲上时,按Up键光标
				cur = n;
				begin = n-3;
				continue;
			}
			if (begin==n-3 && cur == n && ch[i] == 'D') { // 光标在最后一页,最后一首歌曲时,按Down键光标
				cur   = 1;
				begin = 1;
				continue;
			}
			if (ch[i] == 'U' && begin==cur ) { 	// 光标在非第一页,第一首歌曲时,按Up键后,从当前歌曲的上一首开始显示,光标也挪到上一首歌曲。
				cur  -= 1;
				begin-= 1;
				continue;
			}
			if (ch[i] == 'D' && begin+3==cur) {
				cur  += 1;
				begin+= 1;
				continue;
			}
			if(ch[i] == 'U'){ 
				cur -= 1;
			}else{
				cur += 1;
			}
		}
		System.out.println(begin + " " + (begin + 1) + " " + (begin + 2)+ " " + (begin + 3));
		System.out.println(cur);
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		while (input.hasNextInt()) {
			int n = input.nextInt(); // 歌曲数量
			String str = input.next(); // 操作序列
			if (n<=4) 
				MP3PlayerLow4(str, n);
			else
				MP3PlayerUp4(str, n);
		}
	}
}


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

查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。

//Longest common substring 最长公共子串.子串是连续的。
//和之前的LCS(Longest common subsequence---最长公共子序列)不太一样,子序列不一定是连续的。 
//不连续时,在求出dp矩阵后逆向求lcs时,返回路径既可以按↖方向走,也可以按←或↑走。 
//连续时,逆向求lcs时只能按↖走。不过看题解中,有人直接在求dp时,就限制只能按↘方向动态求dp。学习了~ . 

#include 
#include 
#include
using namespace std;

string LCCS(const string& str1, const string& str2) {
	string ret;
	int sz1 = str1.size(), sz2 = str2.size();
	vector<vector<int> > dp(sz1 + 1, vector<int>(sz2 + 1, 0));
	for (int i = 1; i <= sz1; ++i) {
		for (int j = 1; j <= sz2; ++j) {
			if (str1[i - 1] == str2[j - 1]) {
				dp[i][j] = dp[i - 1][j - 1] + 1;
				if (dp[i][j] > ret.size())
					ret = str1.substr(i - dp[i][j], dp[i][j]);
			}
		}
	}
	return ret;
}

int main() {
	string str1, str2;
	while (cin >> str1 >> str2) {
		if (str1.size() > str2.size())
			swap(str1, str2);
		cout << LCCS(str1, str2) << endl;
	}
	return 0;
}
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String s1 = sc.next();
            String s2 = sc.next();
   
            getcommenstrLength(s1,s2);
        }
    }
       
    private static void getcommenstrLength(String s1, String s2){
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        int[][] dp = new int[c1.length+1][c2.length+1];
        int max = 0;
        int num=0;
        StringBuffer sb=new StringBuffer();
       //第一步,得到动态序列
        for(int i = 1; i< c1.length+1; i++){
            for(int j = 1; j< c2.length+1; j++){
                if (c1[i-1] == c2[j-1]){
                    dp[i][j] = dp[i-1][j-1]+1;
                   // if(dp[i][j]> max )   
                   //     max = dp[i][j];             //此处不同,不必返回动态序列情况,我们想要得到的只是整个动态序列
                    //    num=i;
                }
            }
        }
        //根据题中要求,在得到dp后,根据dp定位字符串位置
        if(c1.length < c2.length)
            for(int i = 0;i<c1.length;i++)
                for(int j = 0;j<c2.length;j++){
                    if(dp[i][j] > max){
                        max = dp[i][j];
                        num = i;
                    }
                }
        else {
            for(int i = 0;i<c2.length;i++)
                for(int j = 0;j<c1.length;j++){
                    if(dp[j][i] > max){
                        max = dp[j][i];
                        num = j;
                    }
                }
        }
        for(int i=num-max;i<num;i++){
            sb.append(c1[i]); 
        }
        System.out.println(sb.toString());
    }
} 

HJ66 配置文件恢复

import java.util.*;

public class Main {
	
	public static boolean isMatch(String src, String des){
		char[] c1 = src.toCharArray();
		char[] c2 = des.toCharArray();
		int i = 0;
		while(i < c1.length && i < c2.length){
			if(c1[i] == c2[i])
				i++;
			else
				break;
		}
		if(i == c1.length)
			return true;
		else 
			return false;
	}
	
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        HashMap<String, String> hMap = new HashMap<>();
        hMap.put("reset", "reset what");
        hMap.put("reset board", "board fault");
        hMap.put("board add", "where to add");
        hMap.put("board delet", "no board at all");
        hMap.put("reboot backplane", "impossible");
        hMap.put("backplane abort", "install first");
        while (scanner.hasNext()) {
        	String[] strs = scanner.nextLine().split(" ");
        	int count = 0; // 记录匹配个数
        	Set<String> set = hMap.keySet();
        	String key = "";
        	for(String s : set){
        		String[] temps = s.split(" ");
        		if(temps.length == strs.length){
        			int i = 0;
        			while(i < temps.length){
        				if(isMatch(strs[i], temps[i]))
        					i++;
        				else
        					break;
        			}
        			if(i == temps.length){ // 找到匹配
        				key = s;
        				count++;
        			}       				
        		}
        	}
        	if(count != 1)
        		System.out.println("unkown command");
        	else
        		System.out.println(hMap.get(key));
        		
        }
        scanner.close();
    }
}

HJ67 24点游戏算法

本题对数字选取顺序无要求,但每个数字仅允许使用一次,且需考虑括号运算

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		double result=0.0;
		int[] num=new int[4];
		while(input.hasNext()){
			int[] temp=new int[4];
			for(int i=0;i<4;i++){
				num[i]=input.nextInt();
			}
			System.out.println(check(num,temp,result));
		}
		input.close();
	}

	private static boolean check(int[] num,int[] temp,double result) {
		for(int i=0;i<num.length;i++){
			if(temp[i]==0){
				temp[i]=1;
				if(check(num,temp,result+num[i])
						|| check(num,temp,result-num[i])
						|| check(num,temp,result*num[i])
						|| check(num,temp,result/num[i])){
					return true;
				}
				temp[i]=0;
			}
		}
		if(result==24){
			return true;
		}else{
			return false;
		}
	}
}

HJ68 成绩排序

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            //处理输入和标志
            int n = sc.nextInt();
            boolean flag = sc.nextInt()==1;
            List<Node> list = new ArrayList<>();
            for(int i=0; i<n; i++){
                list.add(new Node(sc.next(), sc.nextInt()));
            }
            //升序还是降序排列
            if(flag) Collections.sort(list, (a, b)->{return a.score-b.score;});
            else Collections.sort(list, (a, b)->{return b.score-a.score;});
            //输出结果
            for(Node node : list){
                System.out.println(node.name+" "+node.score);
            }
        }
    }
}

//构造 姓名+成绩 节点
class Node{
    public String name;
    public int score;
    public Node(String name, int score){
        this.name = name;
        this.score = score;
    }
}

//Java 思路
//按插入顺序读,可以用LinkedHashMap 

// 有重复的名字,重复的分数 所以用 name + " " + score 做key,用score做value

//先将分数排序,再遍历分数(该分数i只找一次)

//每次从LinkedHashMap中遍历,找到与i相等的key 

import java.util.*;
public class Main{
    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int order = sc.nextInt();
            ArrayList<Integer> list = new ArrayList();
            LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
            for (int i = 0; i < n; i++) {
                String name = sc.next();
                int score = sc.nextInt();
                list.add(score);
                map.put(name + " " + score, score);
            }
            Collections.sort(list);
            if (order == 0)
                Collections.reverse(list);
            int pre = -1;
            for (int i : list) {
                if (pre == i)
                    continue;
                for (String key : map.keySet()) 
                    if (map.get(key).equals(i))
                        System.out.println(key);
                pre = i;
            }
        }
    }
}

HJ69 矩阵乘法

import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		while(scan.hasNext()){
			//获取行,列信息
			int row1 = scan.nextInt();
			int column = scan.nextInt();
			int column2 = scan.nextInt();
			int[][] first = new int[row1][column];
			int[][] second = new int[column][column2];
			int[][] temp = new int[row1][column2];
			//将数组存储在数组中
			for(int i=0;i<row1;i++){
				for(int j=0;j<column;j++){
					first[i][j]=scan.nextInt();
				}
			}
			for(int i=0;i<column;i++){
				for(int j =0;j<column2;j++){
					second[i][j]=scan.nextInt();
				}
			}
			//对数组进行计算
			for(int i=0;i<row1;i++){
				for(int j=0;j<column2;j++){
					for(int k= 0;k<column;k++){
						temp[i][j] += first[i][k]*second[k][j];
					}
				}
			}
                        //按照格式输出
			for(int i=0;i<row1;i++){
				StringBuilder sb = new StringBuilder();
				for(int j=0;j<column2;j++){
					if(j==column2-1){
						sb.append(temp[i][j]);
					}else{
						sb.append(temp[i][j]+" ");
					}
				}
				System.out.println(sb.toString());
			}
		}
	}
}

HJ70 矩阵乘法计算量估算


import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            int n=in.nextInt();
            int[][] a=new int[n][2];
            for(int i=0;i<a.length;i++){
                for(int j=0;j<a[0].length;j++){
                    a[i][j]=in.nextInt();
                }
            }
            String str=in.next();
            System.out.println(getTimes(a,str));
        }
    }
    
    public static int getTimes(int [][] a,String str){
        int sum=0;
        int n=a.length-1;
        Stack<Integer> stack =new Stack<Integer>();
        for(int i=str.length()-1;i>=0;i--){
            char s=str.charAt(i);
            if(s==')'){
                stack.push(-1);
            }
            else{
                if(s=='('){
                    int b=stack.pop();
                    int c=stack.pop();
                    sum+=a[b][0]*a[c][0]*a[c][1];
                    a[b][1]=a[c][1];
                    stack.pop();
                    stack.push(b);
                }
                else{
                    stack.push(n);
                    n--;
                }
            } 
        }
        return sum;
    }
}
    

HJ71 字符串通配符

动态规划,记字符串为s,模式串为p,初始化动规矩阵dp[s.length()+1][p.length()+1],dp[i][j]表示字符串s[0:i-1]和模式串p[0:j-1]是否能匹配。有如下几种情况要考虑:
(1) 空模式串和空字符串是能够匹配的:dp[0][0]=true(2) 如果模式串为空,肯定都不匹配,第0列全部为false(3) 对于空字符串,只有全是*的模式串才能匹配上;
(4) 如果模式串和字符串均不为空,对于s[0:i-1]和p[0:j-1]:
i) 若p[j-1]=*,由于*号可以忽略掉,所以此时s[0:i-1]和p[0:j-1]能不能匹配上取决于s[0:i-2]和p[0:j-1]能否匹配上,或者s[0:i-1]和p[0:j-2]能否匹配上。两个中有一个能匹配上,s[0:i-1]和p[0:j-1]就能匹配上。
ii) 若p[j-1]=?或者s[i-1]=p[j-1],此时s[0:i-1]和p[0:j-1]能不能匹配上取决于s[0:i-2]和p[0:j-2]能否匹配上,能匹配上s[0:i-1]和p[0:j-1]就能匹配上,否则匹配不上。
import java.lang.String;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String pattern;
        while((pattern = br.readLine()) != null) {
            pattern = pattern.trim();
            String str = br.readLine().trim();
            System.out.println(isMatch(pattern, str));
        }
    }
    
    private static boolean isMatch(String p, String s) {
        int plen = p.length();
        int slen = s.length();
        boolean[][] dp = new boolean[slen + 1][plen + 1];
        // 字符串和模式串均为空,直接匹配上
        dp[0][0] = true;
        // 模式串为空,全都不匹配,j=0时全部为false
        // i=0时,只有在模式串为*的时候才能匹配
        for(int j = 1; j <= plen; j++){
            if(p.charAt(j - 1) == '*')
                dp[0][j] = true;
            else
                break;
        }
        for(int i = 1; i <= slen; i++){
            for(int j = 1; j <= plen; j++){
                if(p.charAt(j - 1) == '*')
                    dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
                else if(p.charAt(j - 1) == '?' || p.charAt(j - 1) == s.charAt(i - 1))
                    dp[i][j] = dp[i - 1][j - 1];
            }
        }
        return dp[slen][plen];
    }
}

HJ74 参数解析

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        StringBuffer sb = new StringBuffer();
        int len = 0;
        int quotaNum = 0;
        for (int i = 0; i < str.length(); i++){
            if (str.charAt(i) == '\"'){ 
                quotaNum++; 
                continue;
            }
            if (str.charAt(i) != ' '){
                sb.append(str.charAt(i));
            } else if (quotaNum % 2 == 0){ 
                sb.append('\n');
                len++;
            }else {
                sb.append(' ');
            }
        }
        System.out.println(len+1);
        System.out.println(sb.toString());

    }
}


HJ75 公共子串计算

最长公共子串和最长公共子序列。。。傻傻烦不清楚

举个栗子:
str1="123ABCD456"  str2 = "ABE12345D"
最长公共子串是:123
最长公共子序列是:12345

这两个都可以用动态规划,只是状态转移方程有点区别

最长公共子序列是:
dp[i][j] -- 表示子串str1[0...i]和子串str[0...j]的最长公共子序列
当str1[i] == str2[j]时,dp[i][j] = dp[i-1][j-1] + 1;
否则,dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
最优解为dp[len1-1][len2-1];

最长公共子串是: dp[i][j] -- 表示以str1[i]和str2[j]为结尾的最长公共子串 当str1[i] == str2[j]时,dp[i][j] = dp[i-1][j-1] + 1; 否则,dp[i][j] = 0;
最优解为max(dp[i][j]),其中0<=i<len1, 0<=j<len2;

so,代码如下: //求最长公共子串
import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		String str1 = "";
		String str2 = "";
		while(sc.hasNext()){
			str1 = sc.next();
			str2 = sc.next();
			System.out.println(getCommonStrLength(str1, str2));
		}
	}

	public static int getCommonStrLength(String str1, String str2){
		
		int len1 = str1.length();
		int len2 = str2.length();
		int[][] dp = new int[len1+1][len2+1];
		
		for(int i=0;i<=len1;i++){
			for(int j=0;j<=len2;j++){
				dp[i][j] = 0;
			}
		}
		
		for(int i=1;i<=len1;i++){
			for(int j=1;j<=len2;j++){
				if(str1.charAt(i-1) == str2.charAt(j-1)){
					dp[i][j] = dp[i-1][j-1] + 1;
				}else{
					dp[i][j] = 0;	//区别在这儿			
				}
			}
		}
		
		int max = 0;
		for(int i=0;i<=len1;i++){
			for(int j=0;j<=len2;j++){
				if(max < dp[i][j])
					max = dp[i][j];
			}
		}
		
		return max;
	}
}

//求最长公共子序列 import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		String str1 = "";
		String str2 = "";
		while(sc.hasNext()){
			str1 = sc.next();
			str2 = sc.next();
			System.out.println(getCommonStrLength(str1, str2));
		}
	}

	public static int getCommonStrLength(String str1, String str2){
		
		int len1 = str1.length();
		int len2 = str2.length();
		int[][] dp = new int[len1+1][len2+1];
		
		for(int i=0;i<=len1;i++){
			for(int j=0;j<=len2;j++){
				dp[i][j] = 0;
			}
		}
		
		for(int i=1;i<=len1;i++){
			for(int j=1;j<=len2;j++){
				if(str1.charAt(i-1) == str2.charAt(j-1)){
					dp[i][j] = dp[i-1][j-1] + 1;
				}else{
					dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);	//区别在这儿			
				}
			}
		}
		return dp[len1][len2];
	}
} 

HJ77 火车进站

import java.util.*;

public class Main {
    static ArrayList<String> l=new ArrayList<String>();    //储存结果
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        	while(in.hasNext()) {
        		l.clear();    //静态变量,每次先清空
        		int nums=in.nextInt();
        		int[] id=new int[nums];
        		Stack<Integer> stack=new Stack<Integer>();
        		for(int i=0;i<nums;i++) {
        			id[i]=in.nextInt();
        		}
        		trainOut(id,0,stack,"",0);
                Collections.sort(l);    //对结果集排序
        		for(String str:l) {
        			System.out.println(str);
        		}
        	}
        	in.close();
    }
        //i为入栈次数,n为出栈次数,str存储一趟结果
    public static void trainOut(int[] id,int i,Stack<Integer> s,String str,int n) {
    	if(n==id.length) {
    		l.add(str);    //如果所有火车均出栈则将当前结果保存
    	}
    	//和下面的顺序可以换
    	if(!s.empty()) {       //栈非空时出栈
    		int temp=s.pop();
    		trainOut(id,i,s,str+temp+" ",n+1);
    		s.push(temp);    //恢复现场
    	}
    	if(i<id.length) {    //若所有火车没有都入栈则入栈
    		s.push(id[i]);    
    		trainOut(id,i+1,s,str,n);
    		s.pop();        //恢复现场
    	}    		
    }
}

HJ82 将真分数分解为埃及分数

import java.util.Scanner;

//评论区 秀儿 的方法,8/11可以分解为8个1/11,裂开
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String[] s = sc.nextLine().split("\\/");
            int num1 = Integer.parseInt(s[0]);
            int num2 = Integer.parseInt(s[1]);
            StringBuilder sb = new StringBuilder();
            for(int i=0; i<num1; i++){
                if(i!=num1-1) sb.append(1+"/"+num2+"+");
                else sb.append(1+"/"+num2);
            }
            System.out.println(sb.toString());
        }
    }
}

HJ88 扑克牌大小

import java.util.*;

public class Main {
	public static String poker = "345678910JQKA2jokerJOKER";
    public static void main(String[] args) throws Exception {
    	Scanner jin = new Scanner(System.in);
    	while(jin.hasNext()) {
    		String s = jin.nextLine();
    		if(s.contains("joker JOKER")) {
    			System.out.println("joker JOKER");
    		}else {
    			String[] str = s.split("\\-");
    			String[] left = str[0].split("\\s");
    			String[] right = str[1].split("\\s");
    			if(left.length == 4 && right.length != 4) {
    				System.out.println(str[0]);
    			}else if(left.length != 4 && right.length == 4) {
    				System.out.println(str[1]);
    			}else if(left.length == right.length) {
    				String larger = poker.indexOf(left[0]) > poker.indexOf(right[0]) ? str[0] : str[1];
    				System.out.println(larger);
    			}else {
    				System.out.println("ERROR");
    			}
    		}
    	}
    }
}

HJ90 合法IP

import java.util.*;
public class Main{
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String ip = sc.nextLine();
            boolean flag = true;
            if (ip.contains("..") == true || Character.isDigit(ip.charAt(0)) == false) 
                flag = false;
            else {
                String[] temp = ip.split("\\.");
                if (temp.length != 4) flag = false;
                else{
                    for (int i = 0; i < temp.length; i++){
                        if (Character.isDigit(temp[i].charAt(0)) == false || 
                           (temp[i].charAt(0) == '0' && temp[i].length() > 1)){
                            flag = false;
                                break;
                        }
                        int num = Integer.parseInt(temp[i]);
                        if (num < 0 || num > 255)
                            flag = false;
                        }
                    }
                 }
            if (flag == true) System.out.println("YES");
            else System.out.println("NO");
        }
    }
}

HJ92 在字符串中找出连续最长的数字串

import java.util.*;
public class Main{
	public static void main(String[] args) {

		Scanner scan=new Scanner(System.in);
		while(scan.hasNext())
		{
			String str1="";
			String str=scan.nextLine();
			for(char ch:str.toCharArray()){
				//将不是数字的字符全部变成a
				if(ch>='0' && ch<='9'){
					str1+=ch;
				}else{
					str1+="a";
				}
			}
			//按a分割
			String[] strs=str1.split("a");
			int max=0;//记录最长的连续数字串的长度
			for(int i=0;i<strs.length;i++){
				max=strs[i].length()>max?strs[i].length():max;
			}
			for(int i=0;i<strs.length;i++){
				if(strs[i].length()==max)
					System.out.print(strs[i]);
			}
			System.out.println(","+max);
		}
	}
}

HJ93 数组分组

HJ103 Redraiment的走法


import java.util.*;

public class Main {
	// 转化成求最长递增子序列
	public static int getMaxSteps(int [] arr ,int n) {
		int [] dp = new int[n];
		for (int i = 0; i < n; i++) {
			dp[i] = 1;
			for (int j = 0; j < i; j++) {
				 if (arr[j]<arr[i]) {
					dp[i] = Math.max(dp[i], dp[j]+1);
				}
			}
		}
		// 找到dp数组中的最大值即可
		int max = 0;
		for (int i = 0; i < dp.length; i++) 
			if (dp[i]>max) {
				max = dp[i];
			}
		return max;
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		while (input.hasNextInt()) {
			int n = input.nextInt();
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = input.nextInt();
			System.out.println(getMaxSteps(a, n));
		}
	}
}

HJ107 求解立方根

你可能感兴趣的:(java,算法,开发语言)