zoukankan      html  css  js  c++  java
  • LeetCode 1593. 拆分字符串使唯一子字符串的数目最大 dfs 哈希

    地址 https://leetcode-cn.com/problems/split-a-string-into-the-max-number-of-unique-substrings/

    给你一个字符串 s ,请你拆分该字符串,并返回拆分后唯一子字符串的最大数目。
    
    字符串 s 拆分后可以得到若干 非空子字符串 ,这些子字符串连接后应当能够还原为原字符串。
    但是拆分出来的每个子字符串都必须是 唯一的 。
    
    注意:子字符串 是字符串中的一个连续字符序列。
    
     
    
    示例 1:
    
    输入:s = "ababccc"
    输出:5
    解释:一种最大拆分方法为 ['a', 'b', 'ab', 'c', 'cc'] 。
    像 ['a', 'b', 'a', 'b', 'c', 'cc'] 这样拆分不满足题目要求,因为其中的 'a''b' 都出现了不止一次。
    示例 2:
    
    输入:s = "aba"
    输出:2
    解释:一种最大拆分方法为 ['a', 'ba'] 。
    示例 3:
    
    输入:s = "aa"
    输出:1
    解释:无法进一步拆分字符串。
     
    
    提示:
    
    1 <= s.length <= 16
    
    s 仅包含小写英文字母

    算法1
    DFS尝试从短至场尝试每种分割
    使用哈希记录使用过的分割 避免切分出相同的单词

    C++ 代码

    class Solution {
    public:
        string reorderSpaces(string text) {
         int l = 0; int r = 0; int space = 0;
        vector<string> words;
        while (l < text.size() && r < text.size()) {
            while (l < text.size()&& text[l] == ' ') { space++; l++; }
            if (l >= text.size()) break;
            r = l;
            while (r < text.size()&& text[r] != ' ') r++;
            string s = text.substr(l, r - l );
            words.push_back(s);
            l = r;
        }
    
        int spaPerWord = 0;
        
        if(words.size()>1)
            spaPerWord = space / (words.size() - 1);
    
        string ans;
        for (int i = 0; i < words.size(); i++) {
            ans += words[i];
            if (i == words.size() - 1) break;
            for (int j = 0; j < spaPerWord; j++) {
                ans += " ";
            }
        }
    
        int leftSpace = space - spaPerWord * (words.size() - 1);
        for (int j = 0; j < leftSpace; j++) {
            ans += " ";
        }
        return ans;
    }
    };
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    寒假学习10
    寒假学习9
    寒假学习8
    寒假学期7
    寒假学习6
    寒假学习5
    寒假学习4
    Notification通知栏的使用
    Service的使用
    BroadcastReceive的使用
  • 原文地址:https://www.cnblogs.com/itdef/p/13707599.html
Copyright © 2011-2022 走看看