遍歷string時 使用for(char& c : s) for(char c : s) 的區別
阿新 • • 發佈:2018-12-30
一道Leetcode上的題目:
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’
and ‘]’, determine if the input string is valid.The brackets must close in the correct order, “()” and “()[]{}” are
all valid but “(]” and “([)]” are not.
有兩個解法
解法一:
class Solution {
public:
bool isValid(string s) {
stack<char> paren;
for (char& c : s) {
switch (c) {
case '(':
case '{':
case '[': paren.push(c); break;
case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break ;
case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break;
case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break;
default: ; // pass
}
}
return paren.empty() ;
}
};
解法二:
class Solution {
public:
bool isValid(string s) {
stack<char> paren;
for (char c : s) {
switch (c) {
case '(':
case '{':
case '[': paren.push(c); break;
case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break;
case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break;
case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break;
default: ; // pass
}
}
return paren.empty() ;
}
};
兩種解法的唯一區別在於第一種解法使用了
for (char& c : s)
第二種使用了
for (char c : s)
結果是第一種方法比第二種方法快得多。雖然原因很簡單,只是一個很基本的道理,但是畢竟初學,還是寫下來記錄一下。
使用
for (char c : s)
時會複製一個s字串再進行遍歷操作,而使用
for (char& c : s)
時直接引用原字串進行遍歷操作,由於複製一個字串花費了大量的時間,所以第一種解法要快於第二種解法。