zoukankan      html  css  js  c++  java
  • [LC] 1055. Shortest Way to Form String

    From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions).

    Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, return -1.

    Example 1:

    Input: source = "abc", target = "abcbc"
    Output: 2
    Explanation: The target "abcbc" can be formed by "abc" and "bc", which are subsequences of source "abc".
    

    Example 2:

    Input: source = "abc", target = "acdbc"
    Output: -1
    Explanation: The target string cannot be constructed from the subsequences of source string due to the character "d" in target string.


    class Solution {
        public int shortestWay(String source, String target) {
            int res = 0;
            int i = 0;
            while (i < target.length()) {
                int next = scan(source, target, i);
                if (i == next) {
                    return -1;
                }
                i = next;
                res += 1;
            }
            return res;
        }
        
        private int scan(String source, String target, int i) {
            for (char c: source.toCharArray()) {
                if (i != target.length()) {
                    char cur = target.charAt(i);
                    if (c == cur) {
                        i += 1;
                    }
                }
            }
            return i;
        }   
    }
  • 相关阅读:
    Java数组和方法
    Java数组
    Java方法升级
    Java流程控制
    Java编译器的常量优化
    chrome使用技巧(看了定不让你失望)
    C 排序法
    mysql 线程池 数据库连接池
    php mysql
    深入剖析PHP输入流 php://input (转载 http://www.nowamagic.net/academy/detail/12220520)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12294528.html
Copyright © 2011-2022 走看看