Example #1
0
void BriandaisTrie::remove(string word)
{
    if (word.empty()) {
        return;
    }

    /* Deleting the key deletes the word */
    if (word.length() == 1 && word.front() == m_char) {
        m_key = false;
    }

    if (word.front() == m_char && m_child) {
        string w(word);

        m_child->remove(w.erase(0, 1));

        /* If there is no words left in the subtree we can remove it safely */
        if (m_child->countWords() == 0) {
            delete m_child;
            m_child = NULL;
        }
    }
    else if (word.front() != m_char && m_right) {
        m_right->remove(word);
    }
}
Example #2
0
void BriandaisTrie::insert(string word)
{
    if (word.empty()) {
        return;
    }

    if (m_char == '\0') {
        m_char = word.front();
    }

    /* If we are inserting the last matching character, this node is marked as a key */
    m_key |= (word.front() == m_char && word.length() == 1);

    if (word.front() == m_char && word.length() > 1) {
        string w(word);

        if (m_child == NULL) {
            m_child = new BriandaisTrie();
        }

        /* Insert the string minus the first letter */
        m_child->insert(w.erase(0, 1));
    }
    else if (word.front() != m_char) {
        if (m_right == NULL) {
            m_right = new BriandaisTrie();
        }

        m_right->insert(word);
    }
}
Example #3
0
// 将两个字符串形式表示的非负整数进行相加操作,返回字符串表示的结果。
string add(string number1, string number2)
{
    if (number1.front() == '-')
        return subtract(number2, number1.substr(1));

    if (number2.front() == '-')
        return subtract(number1, number2.substr(1));
    
    // 将结果保存在字符串number1中,为了相加方便,调整加数,使得第一个加数的数位
    // 总是大于第二个加数的数位。由于两个正数相加,和的数位最多为两个加数数位较大值
    // 加一,可以预先分配存储空间以方便计算。
    if (number1.length() < number2.length())
        number1.swap(number2);
    number1.insert(number1.begin(), '0');

    // 相加时从低位开始加。初始时进位为0。由于字符串中保存的是数位的ASCII码字符,
    // 需要做相应的转换,使之成为对应的数字值。当前的数位为模基数的值,进位则为除
    // 基数的值。
    int carry = 0, i = number1.length() - 1, j = number2.length() - 1;
    for (; i >= 0; i--, j--)
    {
        int sum = number1[i] - '0' + (j >= 0 ? (number2[j] - '0') : 0) + carry;
        number1[i] = sum % BASE + '0';
        carry = sum / BASE;
    }

    // 移除前导0。
    zeroJustify(number1);

    return number1;
}
Example #4
0
int BriandaisTrie::prefix(string word)
{
    if (word.empty()) {
        return 0;
    }

    if (word.length() == 1 && word.front() == m_char) {
        int count = (int)m_key;

        if (m_child) {
            count += m_child->countWords();
        }

        return count;
    }

    if (word.front() == m_char && m_child) {
        string w(word);

        return m_child->prefix(w.erase(0, 1));
    }
    else if (word.front() != m_char && m_right) {
        return m_right->prefix(word);
    }

    return 0;
}
void process_str(string str)
{
    str = str.substr(1, str.length()-2);

    int val = -1;
    char temp[300] = "";

    if('0' <= str.front() && str.front() <= '9') {
        if(str.back() == 'L' || str.back() == 'R')
            sscanf(str.c_str(), "%d,%s", &val, temp);
        else
            sscanf(str.c_str(), "%d", &val);
    }
    else {
        isInvalid = true;
        return;
    }

    str = string(temp);

    if(val < 0 || pathSet.find(str) != pathSet.end()) {
        isInvalid = true;
        return;
    }

    pathSet.insert(str);

    vec.push_back(make_pair(str, val));
}
Example #6
0
HttpResponse processRequest(HttpRequest r, string dir){

	HttpResponse resp;
	string url;
	string error;

	// cout << "-----" << endl << "URL: " << r.getUrl() << endl;
	// cout << "Directory: " << dir << endl << "-----" << endl;

	//Check if this is a relative dir
	if(dir.front() == '.' && dir.size()>1){
		dir.erase(0,2);
	}

	//check if this is root
	if(dir.back()=='/' && dir.size()==1){
		url = string("/") + r.getUrl();
		cout << url << endl;

	}else if(dir.front() =='.'){
		url = r.getUrl();

	}else if(dir.back()=='/'){ //check for trailing slash
		url = dir + r.getUrl();
		cout << url << endl;
	}else{
		url = dir + "/" + r.getUrl();
		cout << url << endl;
	}

	if (url.back() == '/')
		url = url + "index.html";
	try {
		std::ifstream in(url.c_str());
		ByteBlob contents((std::istreambuf_iterator<char>(in)),
		    std::istreambuf_iterator<char>());
		//cout << contents << '\n';
		if(contents.empty()){
			resp.setStatus(HttpResponse::NF_404);
			return resp;
		}

		// resp.setHeader("content-length", "text/html; charset=UTF-8");
		// resp.setHeader("Accept", "text/html,application/xhtml+xml");
		//resp.setHeader("Accept-Language", "en-us,en;q=0.5");
		resp.setData(contents);
		resp.setStatus(HttpResponse::OK_200);
		//in.close();
	}	catch (...){
		resp.setStatus(HttpResponse::BR_400);
	}

	resp.setHeader("content-language", "en");
	resp.setHeader("content-type", "text/html; charset=UTF-8");

	return resp;
}
Example #7
0
string operator / (string const& lhs, string const& rhs) {
  if (lhs.empty() || rhs.empty()) return lhs + rhs;
  bool left = (lhs.back() == '\\' || lhs.back() == '/');
  bool right = (rhs.front() == '\\' || rhs.front() == '/');
  if (left && right) {
    string res = lhs;
    res.pop_back();
    return res + rhs;
  } else if (!left && !right) {
    return lhs + path::sep + rhs;
  } else {
    return lhs + rhs;
  }
}
    int countStrobogrammaticUntil(string num, bool can_start_with_0) {
        if (can_start_with_0 && cache.find(num) != cache.end()) {
            return cache[num];
        }

        int count = 0;
        if (num.length() == 1) {
            for (const auto& c : {'0', '1', '8'}) {
                if (num.front() >= c) {
                    ++count;
                }
            }
            cache[num] = count;
            return count;
        }
        
        for (const auto& kvp : lookup) {
            if (can_start_with_0 || kvp.first != '0') { 
                if (num.front() > kvp.first) {
                    if (num.length() == 2) {  // num is like "21"
                        ++count;
                    } else {  // num is like "201"
                        count += countStrobogrammaticUntil(string(num.length() - 2, '9'), true);
                    }
                } else if (num.front() == kvp.first) {
                    if (num.length() == 2) {  // num is like 12".
                        count += num.back() >= kvp.second;
                    } else {
                        if (num.back() >= kvp.second) {  // num is like "102".
                            count += countStrobogrammaticUntil(getMid(num), true);
                        } else if (getMid(num) != string(num.length() - 2, '0')) {  // num is like "110".
                            count += countStrobogrammaticUntil(getMid(num), true) -
                                     isStrobogrammatic(getMid(num));
                        }
                    }
                }
            }
        }

        if (!can_start_with_0) { // Sum up each length.
            for (int i = num.length() - 1; i > 0; --i) {
                count += countStrobogrammaticByLength(i);
            }
        } else {
            cache[num] = count;
        }

        return count;
    }
Example #9
0
// static
bool EditableMapObject::ValidateEmail(string const & email)
{
  if (email.empty())
    return true;

  if (strings::IsASCIIString(email))
    return regex_match(email, regex(R"([^@\s]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$)"));

  if ('@' == email.front() || '@' == email.back())
    return false;

  if ('.' == email.back())
    return false;

  auto const atPos = find(begin(email), end(email), '@');
  if (atPos == end(email))
    return false;

  // There should be only one '@' sign.
  if (find(next(atPos), end(email), '@') != end(email))
    return false;

  // There should be at least one '.' sign after '@'
  if (find(next(atPos), end(email), '.') == end(email))
    return false;

  return true;
}
Example #10
0
NestedInteger parser(string s)
{
	if (s.front() == '[')
	{
		NestedInteger list(NestedInteger::ELEM_LIST);
		size_t ppos = 1;
		while (ppos != string::npos)
		{
			auto pos = s.find_first_of(',', ppos);
			string temp(s, ppos, pos -1);
			ValueT value(stoi(temp));
			list.addInterger(value);

			ppos = pos+1;
		}
	}
	else
	{
		//auto pos = s.find_first_of(',');
		
		//string temp(s.c_str(), pos-1);
		NestedInteger value(NestedInteger::ELEM_SINGLE);
		int n = stoi(s);
		cout << "n = " << n << endl;
		value.setValue(n);
		return value;
	}
}
Example #11
0
bool NameDialog::AskForName(QWidget *parent, const QString &title,
		const QString &text, string &str, const QString &placeHolder,
		int maxSize)
{
	if (maxSize <= 0 || maxSize > 32767)
		maxSize = 256;

	NameDialog dialog(parent);
	dialog.setWindowTitle(title);
	dialog.ui->label->setText(text);
	dialog.ui->userText->setMaxLength(maxSize);
	dialog.ui->userText->setText(placeHolder);
	dialog.ui->userText->selectAll();

	bool accepted = (dialog.exec() == DialogCode::Accepted);
	if (accepted) {
		str = QT_TO_UTF8(dialog.ui->userText->text());

		while (str.size() && IsWhitespace(str.back()))
			str.erase(str.end() - 1);
		while (str.size() && IsWhitespace(str.front()))
			str.erase(str.begin());
	}

	return accepted;
}
Example #12
0
string convertBase(const string &input, const int &b1, const int &b2)
{
	bool negativeNum = (input.front() == '-');
	int x  = 0;

	for (int i = (negativeNum ? 1 : 0) ; i < input.size(); i++)
	{
		x *= b1;
		x += isdigit(input[i]) ?   input[i]-'0'  :  tolower(input[i])-'a'+10;
	}

	string answer;
	while(x)
	{
		int r = x % b2;		// remainder
		answer.push_back(r >= 10 ? 'A'+r-10 : '0' + r); // handle for hexadecimal numbers
		x = x / b2;  
	}
	if (answer.empty())
	{
		answer.push_back('0');
	}
	if (negativeNum)
	{
		answer.push_back('-');
	}
	reverse(answer.begin(), answer.end());
	return answer;
}
Example #13
0
bool IsRelativePath(const string &path)
{
  if(path.empty())
    return false;

  return path.front() != '/';
}
Example #14
0
bool ExtractIfExistCommand(string &strCommandText)
{
	bool Result=true;
	const wchar_t *wPtrCmd=PrepareOSIfExist(strCommandText);

	// Во! Условие не выполнено!!!
	// (например, пока рассматривали менюху, в это время)
	// какой-то злобный чебурашка стер файл!
	if (wPtrCmd)
	{
		if (!*wPtrCmd)
		{
			Result=false;
		}
		else
		{
			// прокинем "if exist"
			if (strCommandText.front() == L'@')
			{
				strCommandText.resize(1);
				strCommandText += wPtrCmd;
			}
			else
			{
				strCommandText = wPtrCmd;
			}
		}
	}

	return Result;
}
Example #15
0
string trim(string line)
{
    while (line.length() && isblank(line.back()))
        line.erase(line.end() - 1);
    while (line.length() && isblank(line.front()))
        line.erase(line.begin());
    return line;
}
Example #16
0
    void solve(string seen, string rest, int target, int ans){
        //cout << ans << " " << rest << endl;
        if(rest.empty()){
            if(target==ans) tot.push_back(seen);
        }else{
            int temp=0;
            if(seen.empty()){
                seen+=to_string(rest.front()-'0');
				solve(seen, rest.substr(1), target, rest.front()-'0');
            }else{
                string t1=to_string(rest.front()-'0');
                solve(seen+"+"+t1, rest.substr(1), target, ans+(rest.front()-'0'));
                solve(seen+"-"+t1, rest.substr(1), target, ans-(rest.front()-'0'));
                solve(seen+"*"+t1, rest.substr(1), target, ans*(rest.front()-'0'));
            }
        }
    }
Example #17
0
// 将R进制数转换为十进制数,假设转换得到的数值均在整数数据类型表示的范围内。
int convertRToDecimal(string textOfNumber, int base)
{
    // 处理符号位。
    int sign = 1;
    if (textOfNumber.front() == '+' || textOfNumber.front() == '-')
    {
        sign = textOfNumber.front() == '+' ? 1 : -1;
        textOfNumber.erase(textOfNumber.begin());
    }

    // 将字符串表示的数字从左至右进行转换。
    int number = 0;
    for (auto digit : textOfNumber)
        number = number * base + (digit - '0');

    // 返回的数值需要乘以符号位。
    return sign * number;
}
 bool isValid(string &seg,int prev_pos,string &s,int dot_left)
 {
     int length=s.size()-prev_pos;
     if(atoll(seg.c_str())>255||
         length>3*(dot_left+1)||
         length<dot_left+1||
         (seg.front()=='0'&&seg.size()>1)) return false;
     return true;
 }
Example #19
0
string strToNum(string str)
{
	string num;
	int i = 0;
	int len = str.size();
	while(str.size() != 0)
	{
		switch (str.front())
		{
		case 'y':
			num.push_back('1');
			str.erase(0, 2);
			break;
		case 'e':
			num.push_back('2');
			str.erase(0, 2);
			break;
		case 's':
			if (str.at(1) == 'i')
			{
				num.push_back('4');
				str.erase(0, 2);
			}
			else
			{
				num.push_back('3');
				str.erase(0, 3);
			}
			break;
		case 'w':
			num.push_back('5');
			str.erase(0, 2);
			break;
		case 'l':
			num.push_back('6');
			str.erase(0, 3);
			break;
		case 'q':
			num.push_back('7');
			str.erase(0, 2);
			break;
		case 'b':
			num.push_back('8');
			str.erase(0, 2);
			break;
		case 'j':
			num.push_back('9');
			str.erase(0, 3);
			break;

		default:
			break;
		}
	}
	return num;
}
Example #20
0
bool Information::HasCondition(const string &condition) const
{
	if(condition.empty())
		return true;
	
	if(condition.front() == '!')
		return !HasCondition(condition.substr(1));
	
	return conditions.count(condition);
}
Example #21
0
string encodeWithDigits(string word) {
	string result {digitFor(word.front())};
	for (auto c : rest(word)) {
		auto digit = digitFor(c);
		if (result.back() != digit && !oneof(c, "hw")) {
			result.push_back(digit);
		}
	}
	return result;
}
Example #22
0
// format: SUN, 03 DEC 1996 09:10:35 GMT
void parse(string line)
{
    istringstream iss(line);
    iss >> sDayOfWeek >> sDayOfMonth >> sMonth >> sYear >> sTime >> sTimezone;
    
    sDayOfWeek.pop_back();
    dayOfWeek = find(dayName, dayName + 7, sDayOfWeek) - dayName;
    //cout << sDayOfWeek << ' ' << dayName[dayOfWeek] << '\n';
    
    dayOfMonth = stoi(sDayOfMonth);
    //cout << sDayOfMonth << ' ' << dayOfMonth << '\n';
    
    month = find(monthName, monthName + 12, sMonth) - monthName;
    //cout << sMonth << ' ' << monthName[month] << '\n';
    
    year = stoi(sYear);
    if (sYear.length() == 2) year += 1900;
    //cout << sYear << ' ' << setfill('0') << setw(4) << year << '\n';
    
    hour = stoi(sTime.substr(0, 2));
    minute = stoi(sTime.substr(3, 2));
    second = stoi(sTime.substr(6, 2));
    
    if (sTimezone == "UT" || sTimezone == "GMT") diffMinute = 180;
    else if (sTimezone == "EDT") diffMinute = 420;
    else if (sTimezone == "CDT") diffMinute = 480;
    else if (sTimezone == "MDT") diffMinute = 540;
    else if (sTimezone == "PDT") diffMinute = 600;
    else
    {
        diffMinute = stoi(sTimezone.substr(1, 2)) * 60 + stoi(sTimezone.substr(3, 2));
        if (sTimezone.front() == '+')
            diffMinute = 180 - diffMinute;
        else
            diffMinute = 180 + diffMinute;
    }
    
    int totalMinute = hour * 60 + minute + diffMinute;
    if (totalMinute >= 0)
    {
        if (totalMinute >= 1440)
        {
            addDay(1);
            totalMinute -= 1440;
        }
    }
    else
    {
        addDay(-1);
        totalMinute += 1440;
    }

    hour = totalMinute / 60;
    minute = totalMinute % 60;
}
void print_topsort(const string& topsort)
{
    cout << topsort.front();

    for (string::size_type i {1}; i < topsort.size(); ++i)
    {
        cout << ' ' << topsort[i];
    }

    cout << '\n';
}
Example #24
0
void postorder(string preorder, string inorder)
{
    if (preorder.length() == 0)
        return;

    // 找到根结点。
    int root = 0;
    for (; root < inorder.length(); root++)
        if (inorder[root] == preorder.front())
            break;

    // 在左子树中递归。
    postorder(preorder.substr(1, root), inorder.substr(0, root));

    // 在右子树中递归。
    postorder(preorder.substr(root + 1), inorder.substr(root + 1));

    // 输出根。
    cout << preorder.front();
}
Example #25
0
// 两个非负整数的乘法。
string multiplicate(string number1, string number2)
{
    int sign = 1;
    
    if (number1.front() == '-')
    {
        sign = sign * (-1);
        number1.erase(number1.begin());
    }
    
    if (number2.front() == '-')
    {
        sign = sign * (-1);
        number2.erase(number2.begin());
    }
    
    // 预分配存储空间。
    string number3(number1.length() + number2.length(), 0);
    
    // 从最低位开始相乘。
    int length1 = number1.length() - 1, length2 = number2.length() - 1;
    for (int i = length1; i >= 0; i--)
		for (int j = length2; j >= 0; j--)
		{
		    int k = number3.length() - 1 - (length1 - i + length2 - j);
			number3[k] += (number2[j] - '0') * (number1[i] - '0');
			number3[k - 1] += number3[k] / BASE;
			number3[k] %= BASE;
		}

    // 将数值转换为对应的数字字符。
	for (int i = 0; i < number3.length(); i++)
        number3[i] += '0';
        
    zeroJustify(number3);
    
    if (sign == -1 && number3 != "0")
        number3.insert(number3.begin(), '-');
    
    return number3;
}
    int strobogrammaticInRange(const vector<pair<char, char>>& nums, const string& low, const string& high, string t, int cnt) {
    	if (high.length() < t.length())
    		return cnt;
    	if (compare(low, t) && compare(t, high))
    		if (t.length() == 1 || t.length() > 1 && t.front() != '0')
    			cnt++;

    	for (auto iter = nums.begin(); iter != nums.end(); ++iter)
    		cnt = strobogrammaticInRange(nums, low, high, string(1, iter->first) + t + string(1, iter->second), cnt);

    	return cnt;
    }
// static
bool EditableMapObject::ValidateWebsite(string const & site)
{
  if (site.empty())
    return true;

  auto const dotPos = find(begin(site), end(site), '.');
  // Site should contain at least one dot but not at the begining/and.
  if (dotPos == end(site) || site.front() == '.' || site.back() == '.')
    return false;

  return true;
}
Example #28
0
    string multiply(string num1, string num2) {
     string result(num1.size()+num2.size(),'0');
            for (int i = num1.size()-1; i >= 0; --i) {
                int carry = 0;
                for (int j = num2.size()-1; carry!=0 || j>=0; --j) {
                    int n_digit =  (j >= 0? (num1[i]-'0')*(num2[j]-'0'):0) + carry;
                    carry = (result[i+j+1] -'0'+ n_digit)/10;

                    result[i+j+1] = '0' + (result[i+j+1] -'0'+ n_digit) % 10;

                }
            }
            if (result.front() == '0')
                result.erase(result.begin());
                
            if (num1.size() == 1 && num1.front() == '0' || num2.size() == 1 && num2.front()=='0') {
                string result2(1,'0');
                return result2;
            }
            return result;
    }
Example #29
0
bool BriandaisTrie::exists(string word)
{
    if (word.empty()) {
        return false;
    }

    if (word.length() == 1) {
        return word.front() == m_char && m_key;
    }

    if (word.front() == m_char && m_child) {
        string w(word);

        return m_child->exists(w.erase(0, 1));
    }
    else if (word.front() != m_char && m_right) {
        return m_right->exists(word);
    }

    return false;
}
Example #30
0
void FTPConnection::CommandReturn(string data)
{
    if (data.empty())
    {
        SendMessage("501 Invalid Argument");
    }

    string filename = mp_Config->GetRootDir();
    if (data.front() == '/')
    {
        filename += data;
    }
    else
    {
        filename += m_Pwd + "/" + data;
    }

    std::ifstream file(filename);

    if (!file)
    {

    }

    SendMessage("150 Opening Data Connection to Send File");

    m_DataSock.connect(m_DataEndpoint);

    const int TMP_BUFFER_SIZE = 4096;

    char tmp_buffer[TMP_BUFFER_SIZE];
    std::streamsize n;
    do
    {
        file.read(tmp_buffer, TMP_BUFFER_SIZE);
        n = file.gcount();

        if (n == 0)
            break;

        asio::write(m_DataSock, asio::buffer(tmp_buffer, n));

        if (!file)
            break;
    } while (n > 0);

    file.close();

    m_DataSock.close();

    SendMessage("226 Transfer complete");
}