zoukankan      html  css  js  c++  java
  • 牛客网——华为机试(题27:查找兄弟单词)(Java)

    题目描述:

    输入描述:

    先输入字典中单词的个数,再输入n个单词作为字典单词。
    输入一个单词,查找其在字典中兄弟单词的个数
    再输入数字n

    输出描述:

    根据输入,输出查找到的兄弟单词的个数

    示例1:

    输入:

    3	abc	bca	cab	abc	1

    输出:

    2	bca

    代码: 

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Arrays;
    
    public class Main {
    	public static void main ( String[] args ) throws IOException {
    		BufferedReader bf = new BufferedReader( new InputStreamReader( System.in) );
    		String s;
    		while( ( s = bf.readLine() ) != null ) {
    		String str[] = s.split("\s+");
    		String brother[] = new String[ str.length ];
    		
    		int n = Integer.parseInt(str[ 0 ]);
    		String words = str[ n + 1 ];
    		int k = Integer.parseInt( str[ str.length - 1 ] );
    		
    		int j = 0;
    		for( int i = 1 ; i <= n ; i++ ) {
    			if ( match( words , str[ i ] ) ) {
    				brother[ j ] = str[ i ];
    				j++;
    			}
    		}
    		
    		String a[] = new String[ j ];
    		for ( int i = 0 ; i < j ; i++ ) {
    			a[ i ] = brother[ i ];
    		}
    
    		
    		if ( j == 0 ) {
    			System.out.println( 0 );
    		}
    		else if ( k - 1 > j ) {
    			System.out.println( j );
    		}
    		else {
    			System.out.println( j );
    			Arrays.sort( a );
    			System.out.println( a[ k - 1 ] );
    		}
    		}
    	}
    	
    	static boolean match( String s1 , String s2 ) {
    		
    		int a1[] = new int[ 26 ];
    		int a2[] = new int[ 26 ];
    		
    		if ( !s1.equals( s2 ) ) {
    			for ( int i = 0 ; i < 26 ; i++ ) {
    				char c = (char) (i + 'a');
    				for ( int j = 0 ; j < s1.length(); j++ ) {
    					if ( c == s1.charAt( j ) ) {
    						a1[ i ]++;
    					}
    				}
    				for ( int k = 0 ; k < s2.length(); k++ ) {
    					if ( c == s2.charAt( k ) ) {
    						a2[ i ]++;
    					}
    				}
    			}
    			int judgement = 0;
    			for ( int i = 0 ; i < 26 ; i++ ) {
    				if ( a1[ i ] != a2[ i ] ) {
    					judgement++;
    				}
    			}
    			
    			if ( judgement == 0 ) {
    				return true;
    			}
    			else {
    				return false;
    			}
    		}
    		
    		else {
    			return false;
    		}
    	}
    }
    
  • 相关阅读:
    51 数据中重复的数字
    64 数据流中的中位数
    79. Word Search
    93. Restore IP Addresses
    547. Friend Circles
    Epplus Excel 导入 MSSQL 数据库
    用来更新服务的bat 脚本
    ASP.Net MVC 引用动态 js 脚本
    8、结构的构造器应该显式调用!!!(坑)
    Task 线程重用导致等待!
  • 原文地址:https://www.cnblogs.com/cg-bestwishes/p/10681154.html
Copyright © 2011-2022 走看看