zoukankan      html  css  js  c++  java
  • 17. 交替字符串

    如果字符串str3能够由str1str2中的字符按顺序交替形成,那么称str3str1str2的交替字符串。例如str1="abc",str2="def",那么"adbecf", "abcdef", "abdecf", "abcdef", "adefbc"等等都为str1str2的交替字符串。更形式化的,str3的生成算法如下:

    str3=""
    while str1不为空 or str2不为空:
      把str1或str2的首字符加入到str3,并从str1或str2中删除相应的字符
    end
    

    给定str1str2,和str3,判断str3是否为str1str2的交替字符串。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication14
    {
        class Program
        {
            static void Main(string[] args)
            {
                string str1 = "abc";
                string str2 = "def";
                string[] str3 = { "adbecf","abcdef","abdecf","abcdef","adefbc"};
                foreach (string str in str3)
                {
                    Console.WriteLine("string 1 is {0}, string 2 is {1}, string 3 is {2}, result:{3}",str1,str2,str,IsAlternatelyString(str1,str2,str));
                }
            }
    
            static bool IsAlternatelyString(string str1, string str2, string str3)
            {
                int i = 0;
                int j = 0;
                int k = 0;
                while (k<str3.Length&&i<str1.Length&&j<str2.Length)
                {
                    if (str1[i] == str3[k])
                    {
                        i++;
                        k++;
                    }
                    else
                    {
                        if (str2[j] == str3[k])
                        {
                            j++;
                            k++;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                while (k<str3.Length&&i<str1.Length)
                {
                    if (str1[i] == str3[k])
                    {
                        i++;
                        k++;
                    }
                    else
                    {
                        return false;
                    }
                }
                while (k<str3.Length&&j<str2.Length)
                {
                    if (str2[j] == str3[k])
                        {
                            j++;
                            k++;
                        }
                        else
                        {
                            return false;
                        }
                }
                return true;
            }
        }
    }
    View Code
  • 相关阅读:
    软件测试面试题及答案【史上最全】
    Loadrunner参数(摘)
    Linux系统的目录结构
    关于梦想(七)
    Mysql基于Linux上的安装
    走进MySQL
    关于梦想(六)
    Jmeter的实例应用
    十种社会中最真实的人际关系
    有些人走了就走了,该在的还在就好
  • 原文地址:https://www.cnblogs.com/Ligeance/p/3542751.html
Copyright © 2011-2022 走看看