zoukankan      html  css  js  c++  java
  • Java for LeetCode 087 Scramble String

    Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

    Below is one possible representation of s1 = "great":

    To scramble the string, we may choose any non-leaf node and swap its two children.

    For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".

    解题思路:

    这道题用的是递归遍历的方法,JAVA实现如下:

    static public boolean isScramble(String s1, String s2) {
    		if (!isMatch(s1, s2))
    			return false;
    		if (s1.length() == 0)
    			return true;
    		else if (s1.length() == 1) {
    			if (s1.charAt(0) == s2.charAt(0))
    				return true;
    			return false;
    		} else if (s1.length() == 2) {
    			if (s1.charAt(0) == s2.charAt(0) && s1.charAt(1) == s2.charAt(1))
    				return true;
    			else if (s1.charAt(1) == s2.charAt(0)
    					&& s1.charAt(0) == s2.charAt(1))
    				return true;
    			return false;
    		}
    		for (int i = 0; i < s1.length() - 1; i++) {
    			if (isScramble(s1.substring(0, i + 1), s2.substring(0, i + 1))
    					&& isScramble(s1.substring(i + 1, s1.length()),
    							s2.substring(i + 1, s1.length())))
    				return true;
                    if (isScramble(s1.substring(0, i + 1),
    					s2.substring(s1.length()-i-1, s1.length()))
    					&& isScramble(s1.substring(i+1, s1.length()),
    							s2.substring(0, s1.length()-i-1)))
    				return true;
    		}
    		return false;
    	}
    
    	static public boolean isMatch(String s1, String s2) {
    		if (s1.length() != s2.length())
    			return false;
    		char[] c1 = s1.toCharArray();
    		char[] c2 = s2.toCharArray();
    		Arrays.sort(c1);
    		Arrays.sort(c2);
    		for (int i = 0; i < c1.length; i++)
    			if (c1[i] != c2[i])
    				return false;
    		return true;
    	}
    
  • 相关阅读:
    linux系统swap分区容量扩展
    linux系统lv_root分区容量扩展
    linux系统创建新LV,挂载新分区。
    linux 服务器重启后lvm 变成inactive状态解决
    Linux下使用fdisk扩大分区容量
    go语言 调用飞书群消息机器人接口
    SpringCloud Sentinel 学习笔记
    Git 笔记整理
    SpringBoot 整合 RabbitMQ 学习笔记
    js递归生成树形结构-vue
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4515990.html
Copyright © 2011-2022 走看看