牛客網演算法題之All-in-All,牛客all-in-all

來源:互聯網
上載者:User

牛客網演算法題之All-in-All,牛客all-in-all
題目:

有兩個字串s 和t,如果即從s 中刪除一些字元,將剩餘的字元串連起來,即可獲得t。則稱t是s 的子序列。
請你開發一個程式,判斷t是否是s的子序列。

輸入描述:

輸入包含多組資料,每組資料包含兩個字串s和t。

它們都由數字和字母組成,且長度小於100000。

輸出描述:

對應每一組輸入,如果t是s的子序列,則輸出“Yes”;否則輸出“No”。

輸入例子:

ABC ABC
ABC AB
ABC DE

輸出例子:

Yes
Yes
No

代碼:
package niuke;import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner read = new Scanner(System.in);        while(read.hasNext())        {            String str1 = read.next();            String str2 = read.next();            judgeStr(str1, str2);        }        read.close();    }    /**     *      * @param source     * @param target     * @return     */    public static int indexOf(char[] source, char[] target) {                int targetCount = target.length;        int sourceCount = source.length;                if (targetCount == 0) {            return 0;        }        char first = target[0];        int max = sourceCount - targetCount;        for (int i = 0; i <= max; i++) {            if (source[i] != first) {                while (++i <= max && source[i] != first)                    ;            }            if (i <= max) {                int j = i + 1;                int end = j + targetCount - 1;                for (int k = 1; j < end                        && source[j] == target[k]; j++, k++)                    ;                if (j == end) {                    return i;                }            }        }        return -1;    }        public static void judgeStr(String str1, String str2)    {        int len1 = str1.length(), len2 = str2.length();                int i = 0, j = 0;                for(; i<len1 && j<len2;)        {            if(str1.charAt(i) == str2.charAt(j))            {                j ++;            }            i ++;        }                if(j == len2)        {            System.out.println("Yes");        }        else        {            System.out.println("No");        }    }}

註解:

題目本身不難,重點是對題目的理解。

代碼中indexOf(String, String)方法為此題的一個錯誤理解,即理解成必須全部包含才能輸出Yes,

如“ABCD" "AB"  輸出 “Yes"

對於“ABCD" "AD" 輸出”No"

但是題目本身的意思是對於“ABCD" "AD" 也要輸出”Yes“  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.