Daily Coding Problem: Problem #685

复制代码
import java.util.*

/**
 * This problem was asked by Facebook.
Given a string and a set of delimiters, reverse the words in the string while maintaining the relative order of the delimiters.
For example, given "hello/world:here", return "here/world:hello"
Follow-up:
Does your solution work for the following cases: "hello/world:here/", "hello//world:here"
 * */
class Problem_685 {
    /*
    * solution: Queue+Stack, Time:O(n), Space:O(n)
    * */
    fun delimitersReverse(s: String, delimiters: CharArray): String {
        val queueForDelimiter = LinkedList<Char>()
        val words = Stack<String>()
        //store the position for delimiter have seen
        var lastIndex = 0
        var i = 0
        while (i < s.length) {
            val char = s[i]
            //meet a delimiter
            if (char in delimiters) {
                //avoid add empty space
                if (i - lastIndex > 1) {
                    words.add(s.substring(lastIndex, i))
                }
                queueForDelimiter.offer(char)
                //update lastIndex
                lastIndex = i + 1
            }
            i++
        }
        //check for a word with no last delimiter
        if (s.last() != queueForDelimiter.first) {
            words.add(s.substring(lastIndex, i))
        }
        val result = StringBuilder()
        //set up for result
        //because words is longer than delimiters
        while (words.isNotEmpty()) {
            if (words.isNotEmpty()) {
                result.append(words.pop())
            }
            if (queueForDelimiter.isNotEmpty()) {
                val poped = queueForDelimiter.pop()
                result.append(poped)
                //check if need insert two same delimiter at same time
                if (poped == queueForDelimiter.peek()) {
                    result.append(queueForDelimiter.pop())
                }
            }
        }
        return result.toString()
    }
}
复制代码

 

posted @   johnny_zhao  阅读(175)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示