一道华为笔试题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tianguiyuyu/article/details/89029690

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Scanner;

/*
 * 
 * 3
2,5,6,7,9,5,7
1,7,4,3,4
 */

public class Main{
	
	public void result(ArrayList<String> array)  //n表示第一行的值,一次要读取多少个
	{
		int length=array.size();  //计算出有多少行
		String regex="(.*)[^a-zA-Z0-9](.*)";  //正则表达式.*表示任意的n个字符
		//用hashmap来去重,输出合法字符串并去重
		HashMap<String,Integer> map=new HashMap<>();
		StringBuilder sb_valid=new StringBuilder();
		StringBuilder sb_invalid=new StringBuilder();
		ArrayList<String> array_valid=new ArrayList<>();
		for(int i=0;i<length;i++)
		{
			String temp=array.get(i);
			//System.out.println(temp);
			if(temp.matches(regex)) //包含非法字符
			{
				sb_invalid.append(temp);
				sb_invalid.append(" ");
				continue;
			}
			
			if(map.get(temp)==null)
			{
				array_valid.add(temp);
				map.put(temp, 1);
				sb_valid.append(temp);
				sb_valid.append(" ");
			}
		}
		System.out.println(sb_valid.toString());  //输出合法字符串并且去重
		System.out.println(sb_invalid.toString());  //输出所有非法字符串
		
		//对合法字符串循环左移10次
		/*
		 * 思路是这样,length表示一个字符串的长度,index表示该字符串中字符的索引,移位=10%length (有一个模运算)
		 * 那么,如果index-移位》=0,那么放入位置就是:index-移位
		 * 如index-移位《0, 那么放入位置就是:length+index-移位
		 */
		int n=array_valid.size();
		StringBuilder s_sb=new StringBuilder();
		for(int i=0;i<n;i++)
		{
			char[] temp_1=array_valid.get(i).toCharArray();
			int temp_length=temp_1.length;
			char[] s_char=new char[temp_length];
			for(int j=0;j<temp_length;j++)
			{
				int shift=10%temp_length;
				if(j-shift>=0)
				{
					s_char[j-shift]=temp_1[j];
				}
				else
				{
					s_char[j+temp_length-shift]=temp_1[j];
				}
			}
			for(char s:s_char)
			{
				s_sb.append(s);
			}
			s_sb.append(" ");
		}
		System.out.println(s_sb.toString());
		
		Collections.sort(array_valid);		
		for(String s:array_valid)
		{
			System.out.print(s+" ");
		}
	}

	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);
		ArrayList<String> array=new ArrayList<String>();
		while(in.hasNext())  //到底输入的时候,怎么退出这个循环 ,in中读取会阻塞,读到end字符会退出,不然没有办法退出,我在这儿花了好多时间,不懂为什么出题者没有设置结束标记 
		{
			String str=in.nextLine();
			str=str.trim();   //去掉两端的空格,这一步解决输入的问题,magic
			if(str.equals(""))
			{
				break;
			}
			array.add(str);
		}
        new Main().result(array);
        
	}

}

猜你喜欢

转载自blog.csdn.net/tianguiyuyu/article/details/89029690