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;
    	}
    
  • 相关阅读:
    [USACO17JAN]Subsequence Reversal序列反转
    P1330 封锁阳光大学
    P1403 [AHOI2005]约数研究
    poj1456——Supermarket
    P1807 最长路_NOI导刊2010提高(07)
    P1137 旅行计划
    P1162 填涂颜色
    P1040 加分二叉树
    P1135 奇怪的电梯
    P1086 花生采摘
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4515990.html
Copyright © 2011-2022 走看看