zoukankan      html  css  js  c++  java
  • 每日一题 为了工作 2020 0331 第二十九题

    /**
    *
    * 问题:判断两个字符串是否为变形词
    * 给定两个字符串str1和str2, 如果str1和str2中出现的字符种类一样且每种字符出现
    * 的次数也一样,那么 str1与 str2互为变形词。
    *
    * 举例:
    * str1 = " 123", str2="231", 返回 true。
    * str1 = "123", str2="2331", 返回 false。
    *
    * 解答:
    * 如果字符串 str1和 str2长度不同, 直接返回 false 。如果长度相同, 假设出现字符的
    * 编码值在 0-255之间, 那么先申请一个长度为256的整型数组 map, map[a]=b代表字符编码为
    * a的字符出现了 b次, 初始时 map[0 .. 255]的值都是 0。然后遍历字符串 str1, 统计每种字
    * 符出现的数量, 比如遍历到字符 'a', 其编码值为97, 则令 map[97]++。这样 map就成了str1
    * 中每种字符的词频统计表。然后遍历字符串str2, 每遍历到一个字符都在 map中把词频减下来, 比
    * 如遍历到字符 'a', 其编码值为 97, 则令 map[97]--, 如果减少之后的值小于O, 直接返回false。
    * 如果遍历完str2, map中的值也没出现负值, 则返回true。
    *
    *
    * @author 雪瞳
    *
    */

    *代码

    public class IsDeformation {
    	
    	public boolean getIsDeformation(String a , String b){
    		
    		if(a.length()!=b.length() || a==null || b==null){
    			return false;
    		}
    		//将字符串转化为字符数组
    		char cha1[] = a.toCharArray();
    		/**
    		 * test
    		 */
    //		System.out.println("初始字符数组");
    //		for(char x :cha1){
    //			System.out.print(x+"	");
    //		}
    		char cha2[] = b.toCharArray();
    		int map[] = new int[256];
    //		System.out.println("
    初始 map数组");
    //		for(int x:map){
    //			System.out.print(x+"	");
    //		}
    		for(int i=0;i<cha1.length;i++){
    			map[cha1[i]]++;
    		}
    //		System.out.println("
    遍历结束 map数组");
    //		for(int x:map){
    //			System.out.print(x+"	");
    //		}
    //		System.out.println();
    		for(int i=0;i<cha2.length;i++){
    			map[cha2[i]]--;
    			if(map[cha2[i]]<0){
    				return false;
    			}
    		}
    		
    		return true;
    	}
    }
    

      

    public class TestIsDeformation {
    	
    	public static void main(String[] args) {
    		TestIsDeformation test = new TestIsDeformation();
    		IsDeformation  idf = new IsDeformation();
    		boolean result = false;
    		String a = "12321";
    		String b = "11223";
    		String c = "abcd";
    		String d = "abcc";
    		result = idf.getIsDeformation(a, b);
    		test.showResult(result);
    		
    		result = idf.getIsDeformation(c, d);
    		test.showResult(result);
    	}
    	public void showResult(boolean flag){
    		if(flag){
    			System.out.println("互为变形词");
    		}else{
    			System.out.println("不是互为变形词");
    		}
    	}
    }
    

      

    *运行结果

     

  • 相关阅读:
    模拟实现atoi函数
    C语言中的字符串函数的实现,strcpy,strlen,strcat,strcmp
    使用repeater实现gridview的功能
    使用NPOI随意创建Excel(含下拉列表)
    使用存储过程来动态调用数据(SELECT)
    判断sql执行效率以及针对临时表的使用
    C#读取Excel显示到repeater中
    ASP.NET使用后台更改前台Style
    js格式化日期
    查询某张表的表结构
  • 原文地址:https://www.cnblogs.com/walxt/p/12604305.html
Copyright © 2011-2022 走看看