2
头图

Interleaved string

Title description: Given three strings s1 , s2 , s3 , please help verify s3 is composed of s1 and s2 interlaced .

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/interleaving-string/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Recursion
  • If the length of the string is all 0, return true directly;
  • When the sum of the length of s1 and the length of s2 is not equal to the length of s3, return false directly;
  • When the length of s1 is 0, that is, s1 has been traversed, it is directly judged whether s2 and s3 are equal;
  • When the length of s2 is 0, that is, s2 has been traversed, it is directly judged whether s1 and s3 are equal;
  • Later, according to whether the first character of s1 and s2 is equal to the first character of s3, this method is called recursively to judge.
package com.kaesar.leetcode.LeetCode_051_100;

public class LeetCode_097 {
    /**
     * 递归
     *
     * @param s1
     * @param s2
     * @param s3
     * @return
     */
    public static boolean isInterleave(String s1, String s2, String s3) {
        // 当字符串长度都为0时,直接返回true
        if (s1.length() == 0 && s2.length() == 0 && s3.length() == 0) {
            return true;
        }
        // 当s1的长度和s2的长度之和不等于s3的长度时,直接返回false
        if (s1.length() + s2.length() != s3.length()) {
            return false;
        }
        // 当s1的长度为0即s1已经遍历完了,直接判断s2和s3是否相等
        if (s1.length() == 0) {
            return s2.equals(s3);
        }
        // 当s2的长度为0即s2已经遍历完了,直接判断s1和s3是否相等
        if (s2.length() == 0) {
            return s1.equals(s3);
        }
        if (s1.charAt(0) == s3.charAt(0) && s2.charAt(0) == s3.charAt(0)) {
            // 递归处理s1的下一个字符和s2和s3的下一个字符 && 递归处理s1和s2的下一个字符和s3的下一个字符
            return isInterleave(s1.substring(1), s2, s3.substring(1)) || isInterleave(s1, s2.substring(1), s3.substring(1));
        } else if (s1.charAt(0) == s3.charAt(0)) {
            //  递归处理s1的下一个字符和s2和s3的下一个字符
            return isInterleave(s1.substring(1), s2, s3.substring(1));
        } else if (s2.charAt(0) == s3.charAt(0)) {
            // 递归处理s1和s2的下一个字符和s3的下一个字符
            return isInterleave(s1, s2.substring(1), s3.substring(1));
        } else {
            // 当s1和s2的下一个字符和s3的下一个字符都不相等时,直接返回false
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(isInterleave("aabcc", "dbbca", "aadbbcbcac"));
    }
}
[Daily Message] encounter adversity, you should be grateful. This is a rare occasion!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!