剑指offer 53、54:表示数值的字符串 、字符流中第一个不重复的字符

53.题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。

class Solution {
public:
    bool isNumeric(char* string)
    {
        bool sign=false,decimal=false,hase=false;
        for(int i=0;string[i]!='\0';++i)
        {
            if(string[i]=='e' || string[i]=='E')
            {
                if(hase || string[i+1]=='\0')
                    return false;
                hase=true;
            }
            else if(string[i]=='.')
            {
                if(decimal || hase)
                    return false;
                decimal=true;
            }
            else if(string[i]=='+' || string[i]=='-')
            {
                if(sign && string[i-1]!='e' && string[i-1]!='E')
                    return false;
                if(!sign && i>0 && string[i-1]!='e' && string[i-1]!='E')
                    return false;
                sign=true;
            }
            else if(string[i]>'9' || string[i]<'0')
                return false;
        }
        return true;
    }

};
# -*- coding:utf-8 -*-
class Solution:
    # s字符串
    def isNumeric(self, s):
        hase=decimial=sign=False
        for i in range(len(s)):
            if s[i]=='e' or s[i]=='E':
                if hase or i==len(s)-1:
                    return False
                hase=True
            elif s[i]=='.':
                if hase or decimial:
                    return False
                decimial=True
            elif s[i]=='+' or s[i]=='-':
                if sign and s[i-1]!='e' and s[i-1]!='E':
                    return False
                if sign==False and i>0 and s[i-1]!='e' and s[i-1]!='E':
                    return False
                sign=True
            elif s[i]>'9' or s[i]<'0':
                return False
        return True

        # write code here

54.题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。

class Solution
{
public:
    string data;
    int table[128]={0};
  //Insert one char from stringstream
    void Insert(char ch)
    {
        data=data+ch;
        ++table[ch];
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        for(int i=0;data[i]!='\0';++i)
            if(table[data[i]]==1)
                return data[i];
        return '#';
    }

};
# -*- coding:utf-8 -*-
class Solution:
    # 返回对应char
    def __init__(self):
        self.string=""
    def FirstAppearingOnce(self):
        index=-1
        for i in range(len(self.string)):
            if self.string.count(self.string[i])==1:
                index=i
                break
        return self.string[index] if index != -1 else "#"

        # write code here
    def Insert(self, char):
        self.string+=char
        # write code here

猜你喜欢

转载自blog.csdn.net/zd_nupt/article/details/81534287