Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1544. Make The String Great

Rain Hu

1544. Make The String Great


一、題目

Given a string s of lower and upper case English letters.
A good string is a string which doesn’t have two adjacent characters s[i] and s[i + 1] where:

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Stack

char trans(char c) {    // 大小寫互換
    return ('a' <= c && c <= 'z') ? c - 32 : c + 32; 
    
}
string makeGood(string s) {
    string st;
    for (char c : s) {
        if (st.empty()) {
            st.push_back(c);
        } else {
            if (st.back() == trans(c)) {        // 當 stack 頂端與下一個字元互為大小寫
                st.pop_back();
            } else {
                st.push_back(c);
            }
        }
    }
    return st;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 901. Online Stock Span
Next
[LeetCode] 2462. Total Cost to Hire K