牛客网|Extract unique integers

Topic information

Enter an int integer, and follow the reading order from right to left, and return a new integer without repeated numbers. Ensure that the last digit of the entered integer is not 0.

Input example: 9876673

Sample output: 37689

answer

The big idea is to disassemble the input into an array of characters, and store the characters in an ordered set. If the character is already contained in the set, skip it, otherwise the characters are put into the set. The collection can choose ArrayList or Deque.

Based on ArrayList and Deque, two implementation methods are given

coding

Method one, after the input numbers are reversed, the characters are stored in the ArrayList and output

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ReverseNonRepetitionIntegers {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
		while ((input = br.readLine()) != null) {
			// 输入数字逆序
			StringBuffer sb = new StringBuffer(input);
			sb.reverse();
			
			// 逆序后数字转化为字符数组
			char[] numArr = sb.toString().toCharArray();
			
			// 遍历数组字符,并将字符入List
			List<Character> list = new ArrayList<>();
			for (char ch : numArr) {
				if (list.contains(ch)) {
					continue;
				} 
				
				list.add(ch);
			}
			
			// 将list中不重复字符输出
			StringBuffer returnSb = new StringBuffer();
			for (char ch : list) {
				returnSb.append(ch);
			}
			
			System.out.println(returnSb.toString());
		}
	}
}
 

Method 2: Convert the input number to a character array, use the first-in-first-out feature of the queue, and output the result number

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Deque;
import java.util.LinkedList;

public class ReverseNonRepetitionIntegers {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
		while ((input = br.readLine()) != null) {
			
			// 将输入数字转为字符数组
			char[] numArr = input.toCharArray();
			
			// 使用队列存放字符,利用队列先进先出特点,最终输出数字
			Deque<Character> list = new LinkedList<>();
			for (int i=numArr.length-1; i>=0; i--) {
				if (!list.contains(numArr[i])) {
					list.push(numArr[i]);
				}
			}
			
			// 队列中有值时,使用pollLast方法,对先入队列的元素先出队列
			while(list.size()>0) {
				System.out.print(list.pollLast());
			}
			
			System.out.println();
		}
	}
}

 

The above two implementation methods, the results of running on Niuke.com are as follows, the second method has a short running time and takes up less memory.

Guess you like

Origin blog.csdn.net/magi1201/article/details/114855605