《程序员代码面试指南》第五章 字符串问题 判断字符数组中是否所有的字符都只出现过一次...

题目
判断字符数组中是否所有的字符都只出现过一次
java代码
package com.lizhouwei.chapter5;

/**
 * @Description: 判断字符数组中是否所有的字符都只出现过一次
 * @Author: lizhouwei
 * @CreateDate: 2018/4/24 21:18
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter5_8 {
    public boolean isUnique(char[] chars) {
        //堆初始化
        for (int i = 0; i < chars.length; i++) {
            heapInsert(chars, i);
        }
        //堆初调整
        for (int i = chars.length - 1; i != 0; i--) {
            swap(chars, 0, i);
            heapify(chars, 0, i);
        }
        for (int i = 1; i < chars.length; i++) {
            if (chars[i] == chars[i - 1]) {
                return false;
            }
        }
        return true;
    }

    public void heapInsert(char[] arr, int index) {
        int parent = 0;
        while (index > 0) {
            parent = (index - 1) / 2;
            if (arr[parent] < arr[index]) {
                swap(arr, parent, index);
                index = parent;
            } else {
                break;
            }
        }
    }

    public void heapify(char[] arr, int index, int heapSize) {
        int left = 2 * index + 1;
        int right = 2 * index + 2;
        int largest = index;
        while (left < heapSize) {
            if (arr[left] < arr[index]) {
                largest = left;
            }
            if (right < heapSize && arr[right] < arr[left]) {
                largest = right;
            }
            if (largest == index) {
                break;
            }
            swap(arr, index, largest);
            index = largest;
            left = 2 * index + 1;
            right = 2 * index + 2;
        }
    }

    public void swap(char[] arr, int a, int b) {
        char temp = arr[b];
        arr[b] = arr[a];
        arr[a] = temp;
    }

    //测试
    public static void main(String[] args) {
        Chapter5_8 chapter = new Chapter5_8();
        char[] chars1 = {'a','b','c'};
        boolean result1 = chapter.isUnique(chars1);
        System.out.println("{'a','b','c'}:中是否有重复字符:" + result1);
        char[] chars2= {'1','2','1'};
        boolean result2 = chapter.isUnique(chars2);
        System.out.println("{'1','2','1'}:中是否有重复字符:" + result2);
    }
}
结果

1369004-20180424220019792-1901814135.png

转载于:https://www.cnblogs.com/lizhouwei/p/8934073.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值