小米OJ(6)交叉队列

描述:

给出三个队列 s1,s2,s3 ,判断 s3 是否是由 s1 和 s2 交叉得来。 如:s1 为 aabcc , s2 为 dbbca。 当 s3 为 aadbbcbcac 时,返回 true(即将 s1 拆成三部分: aa,bc,c 分别插入 s2 对应位置) 否则返回 false。

输入:

aabcc,dbbca,aadbbcbcac

输出: 

true

输入样例: 

aabcc,dbbca,aadbbcbcac
aabcc,dbbca,aadbbbaccc
a,b,ab
a,b,ba
a,b,ac
abc,bca,bcaabc
abc,bca,aabbcc

输出样例: 

 

true
false
true
true
false
true
false

思路: 

输入字符串以“,”分割并且分别赋值给三个字符串对象,然后从第一个字符串对象开始匹配第三个字符串,相应位置字符,没有则将第二个字符串字符进行形同匹配,并通过计数标志进行判断输出。

代码:

import sys

for line in sys.stdin:
    # line = line.split(',')
    # s1,s2,s3=list(line[0]),list(line[1]),list(line[2])
    s1,s2,s3=line.strip().split(',')  #strip()除去字符串头尾的指定字符
    l1,l2,l3=len(s1),len(s2),len(s3)
    print(s3)
    h1=h2=h3=0
    while h3<l3:
        t3=s3[h3]
        if h1<l1 and t3==s1[h1]:
            h1+=1
        if h2<l2 and t3==s2[h2]:
            h2+=1
            
        h3+=1
    
    print(h1,h2,h3)
    print(l1,l2,l3)
    if  h1 == l1 and h2 == l2 and h3 == l3 and l3 == (l1+l2):
        print('true')
    else:
        print('false')

 

### 使用两个栈实现队列的Java代码示例 通过使用两个栈来模拟队列的行为是一种常见的数据结构设计方法。以下是基于此逻辑的一个具体实现: #### 实现原理 为了使两个栈能够完成队列的功能,可以定义一个输入栈 `inStack` 一个输出栈 `outStack`。当执行入队操作时,元素被压入 `inStack`;而当需要出队时,则将所有元素从 `inStack` 转移到 `outStack` 并弹出顶部元素。 ```java import java.util.Stack; class MyQueue { private Stack<Integer> inStack; private Stack<Integer> outStack; /** Initialize your data structure here. */ public MyQueue() { inStack = new Stack<>(); outStack = new Stack<>(); } /** Push element x to the back of queue. */ public void push(int x) { inStack.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if (outStack.isEmpty()) { while (!inStack.isEmpty()) { outStack.push(inStack.pop()); } } return outStack.pop(); } /** Get the front element. */ public int peek() { if (outStack.isEmpty()) { while (!inStack.isEmpty()) { outStack.push(inStack.pop()); } } return outStack.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return inStack.isEmpty() && outStack.isEmpty(); } } ``` 上述代码展示了如何利用两个栈来构建一个基本的队列功能[^1]。其中的关键在于理解何时以及如何在两个栈之间转移数据以保持 FIFO 的顺序。 #### 测试用例 下面是一个简单的测试例子用于验证该类的工作情况: ```java public class Main { public static void main(String[] args) { MyQueue obj = new MyQueue(); obj.push(1); obj.push(2); System.out.println(obj.peek()); // 输出 1 System.out.println(obj.pop()); // 输出 1 System.out.println(obj.empty()); // 输出 false } } ``` 这段程序创建了一个新的队列对象并进行了几个基础的操作演示其行为是否符合预期[^2]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值