ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java 进阶练习题

2021-08-04 20:58:40  阅读:80  来源: 互联网

标签:练习题 字符 Java 进阶 int ++ str 字符串 public


Java 进阶练习题

Java 进阶练习题

1、返回指定目标等于数组中两个数和的下标

题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数(只返回第一次找到的结果),并返回他们的数组下标。

package com.test;

public class Test01 {
    public static void main(String[] args) {
        int target = 3;
        int[] nums = {1, 9, 3, 2, 4, 5};
        int nLen = nums.length;
        for (int i = 0; i < nLen; i++) {
            for (int j = i + 1; j < nLen; j++) {
                int temp = nums[i] + nums[j];
                //找到就结束
                if (temp == target) {
                    System.out.println(i + " " + j);
                    break;
                }
            }
        }
    }
}

2、两个链表数据求和

题目:给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

package com.test;

import java.util.Scanner;

public class ListTest {
    public static void main(String[] args) {
        //输入两个数值,并将数值每个数存入链表
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();

        //创建链表
        ListNode ln1 = createList(a);
        ListNode ln2 = createList(b);

        //链表相加
        ListNode newList = addTowList(ln1, ln2);
        //打印链表
        printList(newList);
    }

    //输出链表数据
    public static void printList(ListNode lnp) {
        while (lnp != null) {
            System.out.print(lnp.val);
            lnp = lnp.next;
        }
        System.out.println();
    }

    //按输入的数据创建链表
    public static ListNode createList(int n) {
        /**
         *  创建链表并赋值:
         *      1、新建链表用于储存当前链表
         *      2、新建链表对象用于储存当前对象
         *      3、向当前链表中添加当前对象
         */

        ListNode ln = new ListNode(0);
        ListNode tln = ln;//中间链表
        while (n != 0) {
            ListNode listNode = new ListNode(n % 10);
            tln.next = listNode;
            tln = listNode;
            n /= 10;
        }
        return ln.next;
    }

    public static ListNode addTowList(ListNode ln1, ListNode ln2) {
        int carry = 0;//进位,则高位加1;不进位,则高位加0
        ListNode newList = new ListNode(0);//返回的两个链表相加的新链表
        ListNode tempList = newList;//中间数组
        while (true) {
            ListNode ln = new ListNode(0);//创建遍历对象,即表示新链表当前对象,只要位数不够,用0补位
            int temp = ln1.val + ln2.val + carry;//每一位相加的和
            //判断是否进位
            if (temp < 10) {
                ln.val = temp;
                carry = 0;
            } else {
                ln.val = temp % 10;
                carry = 1;
            }

            //指向下一项
            tempList.next = ln;
            tempList = ln;

            //判断需要两个相加链表是否为空,必须同时为空,不同时为空则高位补0
            if (ln1.next == null && ln2.next == null && carry == 0) {
                break;
            }

            //判断ln1下一项是否为空,为空则补0
            if (ln1.next != null) {
                ln1 = ln1.next;
            } else {
                ln1 = new ListNode(0);
            }

            //判断ln2下一项是否为空
            if (ln2.next != null) {
                ln2 = ln2.next;
            } else {
                ln2 = new ListNode(0);
            }
        }
        return newList.next;
    }
}

class ListNode {
    public int val;
    public ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }
}

3、求不重复子串最长长度

题目:给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。

package com.training;

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

public class StringTest01 {
    public static void main(String[] args) {
        //待检测字符串
        String str = "1234578423123456";
        System.out.println(getBiggestLen(str));
    }

    public static int getBiggestLen(String str) {
        //字符串转字符数组
        char[] c = str.toCharArray();
        int cLen = c.length;//返回字符数组大小
        int biggestLen = 0;//记录字符串不同最大长度
        //创建动态数组,为了检测当前字符是否与动态数组中的字符重复,并存储当前字符串
        //即动态数组中的字符绝对不重复
        List<Character> list = new ArrayList<>();
        //循环字符数组,检测当前字符是否重复
        for (int i = 0; i < cLen; i++) {
            //判断当前动态数组是否包含当前字符
            //包含当前字符,则删除与当前字符串相同字符之前的字符,形成新的动态数组
            if (list.contains(c[i])) {
                //获取当前动态数组大小,并返回给记录最大长度的变量
                if (list.size() > biggestLen) {
                    biggestLen = list.size();
                }
                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j) != c[i]) {
                        list.remove(j);
                    } else {
                        list.remove(j);
                        break;
                    }
                }
            }
            list.add(c[i]);
        }
        if (list.size() > biggestLen) {
            biggestLen = list.size();
        }
        return biggestLen;
    }
}

4、求有序数组中位数

题目:给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。请你找出这两个有序数组的中位数。

package com.training;

import java.util.Scanner;

public class Median {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        int n = scanner.nextInt();
        
        int []a=getIntArrays(m,scanner);
        int []b=getIntArrays(m,scanner);

        System.out.println(getMedian(a, m));
        System.out.println(getMedian(b, n));
    }

    //创建顺序int数组
    public static int[] getIntArrays(int n, Scanner scanner) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }
        return a;
    }

    //返回中位数,中位数是排序好的数中间的数据,数据长度为奇数,则就是中间的数据;为偶数则是中间两个数据和的一半
    public static double getMedian(int[] a, int n) {
        int mid = n / 2;
        if (n % 2 != 0) {
            return a[mid];
        } else {
            return (a[mid] + a[mid - 1]) / 2.0;
        }
    }
}

5、字符串转数字

题目:请实现一个功能,使其能将字符串转换成整数,非数字字符不输出。

package com.training;

/**
 * @author AdminDGW
 * 实现一个功能,使其能将字符串转换成整数,非数字字符不输出。
 */
public class StringTest02 {
    public static void main(String[] args) {
        String str = ".-1234qq";
        System.out.println(getStrNum(str));
    }

    /**
     * 返回StringBuffer对象
     */
    public static StringBuffer getStrNum(String str) {
        char[] chars = str.toCharArray();
        //StringBuffer对象用于添加字符
        StringBuffer stringBuffer = new StringBuffer();
        int len = str.length();

        for (int i = 0; i < len; i++) {
            //b1:判断数字符号
            boolean b1 = (chars[i] == '-' || chars[i] == '+') &&
                    (chars[i + 1] >= '0' && chars[i + 1] <= '9');
            //b2:判断是否为数字
            boolean b2 = chars[i] >= '0' && chars[i] <= '9';
            //b3:判断小数
            boolean b3 = (chars[0] != '.') && (chars[i] == '.') &&
                    (chars[i - 1] >= '0' && chars[i - 1] <= '9');
            
            if (b1) {
                stringBuffer.append(chars[i]);
            }
            if (b2) {
                stringBuffer.append(chars[i]);
            } else if (b3) {
                stringBuffer.append(chars[i]);
            }
        }
        return stringBuffer;
    }
}

6、自定义字符匹配

题目:给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。

’.’ 匹配任意单个字符

’*’ 匹配零个或多个前面的那一个元素

package com.training;

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

/**
 * @author AdminDGW
 * 题目:给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '\*' 的正则表达式匹配。
 * * '.' 匹配任意单个字符
 * * '*' 匹配零个或多个前面的那一个元素
 */
public class Match {
    public static void main(String[] args) {
        String str1 = "1235a";
        String str2 = ".1.2*3*555a";
        System.out.println(matchString(str1, str2));
    }

    /**
     *
     * @param str1: 匹配字符串
     * @param str2: 有特殊字符的待匹配字符串
     * @return boolean : 是否匹配成功
     */
    public static boolean matchString(String str1, String str2) {
        //字符串转字符数组
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();
        //判断第一个字符,在不是特殊字符的情况下是否相同
        if (chars2[0] != '*' && chars2[0] != '.' && chars1[0] != chars2[0]) {
            return false;
        }
        //两个字符数组长度
        int cLen1 = chars1.length;
        int cLen2 = chars2.length;
        //字符数组转字符集合
        List<Character> list1 = new ArrayList<>();
        for (int i = 0; i < cLen1; i++) {
            list1.add(chars1[i]);
        }
        List<Character> list2 = new ArrayList<>();
        for (int i = 0; i < cLen2; i++) {
            list2.add(chars2[i]);
        }

        //list1循环变量
        int i = 0;
        //list2循环变量
        int j = 0;
        //以下循环后,两个集合长度相等,不等则返回false
        while (j < list2.size()) {
            //防止list1循环变量超过范围
            if (i >= cLen1 - 1) {
                i = cLen1 - 1;
            }
            //判断list2当前字符是否为.
            //是的话,就给list2当前字符赋值当前对应的list1字符
            if (list2.get(j) == '.') {
                list2.remove(j);
                list2.set(j, list1.get(i));
            }
            //判断list2当前字符是否为*
            //是的话,就需要查找list1中对应位置相同的字符个数,以及查找list2中与*之前一个数相同字符的个数
            if (list2.get(j) == '*') {
                list2.remove(j);
                //size1、size2分别记录list1、list2中关于*之后对应相同字符的个数
                int size1 = 0;
                int size2 = 0;
                //查找list1中对应位置相同的字符个数
                for (int k = i; k < cLen1 - 1; k++) {
                    if (!list1.get(k).equals(list1.get(k + 1))) {
                        size1 = k - i;
                        break;
                    }
                }
                //查找list2中与*之前一个数相同字符的个数
                for (int k = j; k < list2.size() - 1; k++) {
                    if (!list2.get(k).equals(list2.get(k + 1))) {
                        size2 = k - j;
                        break;
                    }
                    //判断字符是否到集合结尾还相等
                    if ((list2.get(k).equals(list2.get(list2.size() - 1)))) {
                        size2 = list2.size() - 1 - j;
                    }
                }

                //如果list2中*之后相同字符个数小于list1对应位置相同字符个数,就不能匹配
                if (size2 < size1) {
                    return false;
                }
                //删除多余个数,保证两个集合对应位置字符个数相等
                if (size2 > size1) {
                    for (int k = 0; k < size2 - size1; k++) {
                        list2.remove(j + k);
                    }
                }
            }
            i++;
            j++;
        }
        //两个集合经过上述程序后,字符个数必须相等
        if (list1.size() != list2.size()) {
            return false;
        }
        //遍历判断两个集合中的字符,不相等就放回false
        for (int k = 0; k < cLen1 - 1; k++) {
            if (!list1.get(k).equals(list2.get(k))) {
                return false;
            }
        }
        //经过上述程序没有返回false的情况下,说明两个集合中的字符以及集合大小一致,则返回true
        return true;
    }
}

7、返回字符串最长公前缀

题目:查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 “”。

package com.training;

/**
 * @author AdminDGW
 * 查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。
 */
public class StringTest03 {
    public static void main(String[] args) {
        String[] str = {"a1234", "a123ax", "a123"};
        System.out.println(getStr(str));
    }

    /**
     * 最长公前缀字符串
     * @param str: 字符串数组
     * @return 最长公前缀字符串
     */
    public static String getStr(String[] str) {
        //按字符串长度从小到大排序
        for (int i = 0; i < str.length - 1; i++) {
            for (int j = 0; j < str.length - 1 - i; j++) {
                if (str[j].length() > str[j + 1].length()) {
                    String st = str[j];
                    str[j] = str[j + 1];
                    str[j + 1] = st;
                }
            }
        }
        //先比较前两个字符串中前缀相同的最大字符串
        char[] c1 = str[0].toCharArray();
        char[] c2 = str[1].toCharArray();
        //创建迭代字符串,用于添加相同字符前缀
        String bigStr = "";
        for (int i = 0; i < c1.length; i++) {
            if (c1[i] != c2[i]) {
                break;
            } else {
                bigStr += c1[i];
            }
        }

        //比较之后的字符串最长前缀
        for (int i = 2; i < str.length; i++) {
            char[] c = str[i].toCharArray();
            char[] cb = bigStr.toCharArray();
            for (int j = 0; j < cb.length; j++) {
                if (cb[j] != c[j]) {
                    //只要有与当前最长字符串前缀不相等的情况,就新建最长字符串对象,改变字符串
                    bigStr = new String(cb, 0, j);
                    break;
                }
            }
        }
        return bigStr;
    }
}

8、找出三元组

题目:给定一个整数数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0,找出所有满足条件且不重复的三元组。

下面给出的代码,效率较低。

package com.training;

/**
 * @author AdminDGW
 * 给定一个整数数组 nums,判断 nums 中是否存在三个元素 a,b,c ,
 * 使得 a + b + c = 0,找出所有满足条件且不重复的三元组。
 */
public class SanYuanZu {
    public static void main(String[] args) {
        int[] a = {-1, 2, 1, 3, -3, -2};
        getSan(a);
    }

    public static void getSan(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j < a.length - 1; j++) {
                for (int k = j + 1; k < a.length; k++) {
                    if (a[i] + a[j] + a[k] == 0) {
                        System.out.println(a[i] + " " + a[j] + " " + a[k]);
                    }
                }
            }
        }
    }
}

9、括号匹配

题目:给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]'的字符串,判断字符串是否有效。

有效字符串需满足:左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。注意空字符串可被认为是有效字符串。

package com.training;

/**
 * @author AdminDGW
 * 题目:给定一个只包括 '(',')','{','}','[',']'的字符串,判断字符串是否有效。
 * 有效字符串需满足:左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。注意空字符串可被认为是有效字符串。
 */
public class StringTest04 {
    public static void main(String[] args) {
        String str = "[1[2]3]{1}(1234( ))";
        System.out.println(getMatch(str));
    }

    public static boolean getMatch(String str) {
        char[] c = str.toCharArray();
        //'{'记数
        int count1 = 0;
        //'['记数
        int count2 = 0;
        //'('记数
        int count3 = 0;
        //'}'记数
        int count4 = 0;
        //']'记数
        int count5 = 0;
        //')'记数
        int count6 = 0;

        //判断'{}'的循环变量
        int j = 0;
        //判断'[]'的循环变量
        int k = 0;
        //判断'()'的循环变量
        int r = 0;

        for (int i = 0; i < c.length; i++) {
            if (c[i] == '{') {
                count1++;
                //标志,表示是否存在对应的'}'
                int flag = 0;
                //从'{'的位置向后找,是否有'}',没有直接返回false
                //下次遇见'{',则从上次'}'的j位置开始向后找
                while (j < c.length) {
                    if (c[j] == '}') {
                        flag = 1;
                        break;
                    }
                    j++;
                }
                //如果j循环到字符数组长度,说明没有找到对应的'}'
                if (flag == 0 && j == c.length) {
                    return false;
                }
            }
            //以下代码与上述代码功能类似,但不好集合在一起,为了便于理解,我分开实现对应功能
            if (c[i] == '[') {
                count2++;
                int flag = 0;
                while (k < c.length) {
                    if (c[k] == ']') {
                        flag = 1;
                        break;
                    }
                    k++;
                }
                if (flag == 0 && k == c.length) {
                    return false;
                }
            }
            if (c[i] == '(') {
                count3++;
                int flag = 0;
                while (r < c.length) {
                    if (c[r] == ')') {
                        flag = 1;
                        break;
                    }
                    r++;
                }
                if (flag == 0 && r == c.length) {
                    return false;
                }
            }

            if (c[i] == '}') {
                count4++;
            }
            if (c[i] == ']') {
                count5++;
            }
            if (c[i] == ')') {
                count6++;
            }
        }
        //判断'{}'、'[]'、'()'各自的数量是否相同,不相同直接返回false
        if (count1 != count4 || count2 != count5 || count3 != count6) {
            return false;
        }
        return true;
    }
}

标签:练习题,字符,Java,进阶,int,++,str,字符串,public
来源: https://blog.csdn.net/weixin_43552452/article/details/119393072

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有