码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_171 Excel Sheet Column Number & leetcode_28 Implement strStr()

时间:2015-08-18 10:20:38      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:leetcode   excel sheet column n   implement strstr   

leetcode_171 Excel Sheet Column Number

题目:

Related to question Excel Sheet Column Title

Given a column title as appear in an Excel sheet, return its corresponding column number.

解法:

class Solution {
public:
    int titleToNumber(string s) 
    {
        int num = 0;
        int length = s.size();
        for(int i = length - 1; i >= 0; --i)
        {
            num += pow(26, (length - 1 - i)) * (s[i] - 'A' + 1); 
        }
        return num;
    }
};

leetcode_28 Implement strStr()

题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

解法:

class Solution {
public:
    int strStr(string haystack, string needle) 
    {
        int length_h = haystack.size();
        int length_n = needle.size();
        if(length_h < length_n)
            return -1;        
        if(length_h == 0 || length_n == 0)
            return 0;
        int i = 0;
        while(i <= length_h - length_n)
        {
            int j = 0;
            int tmp = i;
            while(j < length_n)
            {
                if(haystack[tmp] != needle[j])
                    break;
                else
                {
                    ++tmp;
                    ++j;
                    if(j == length_n)
                        return i;
                }
            }
            ++i;
        }
        return -1;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode_171 Excel Sheet Column Number & leetcode_28 Implement strStr()

标签:leetcode   excel sheet column n   implement strstr   

原文地址:http://blog.csdn.net/xwchao2014/article/details/47729705

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!