LeetCode字符串(一)

今天主要刷了以下两道题目:**
https://leetcode.com/problems/judge-route-circle/description/
https://leetcode.com/problems/palindromic-substrings/description/

题目一

> Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
  The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

Example 1:

Input: “UD”
Output: true

Example 2:

Input: “LL”
Output: false

分析:
这道题比较简单,目的就是最终回到原点。简单的方法就是左走了多少步就要右走同样的步数,上下也一样。所以就采取两个变量分别计算上下、左右的步数。最终两个变量还是0,则证明能回到原点。

代码:

class Solution {
public:
        bool judgeCircle(string moves) {
        int yAxis=0,xAxis=0;
        if(moves.size()==0) 
            return false;
        for(int i=0;i<moves.size();i++)
        {
            switch (moves[i])
            {
               case 'U':yAxis++;break;
               case 'D':yAxis--;break;
               case 'R':xAxis++;break;
               case 'L':xAxis--;break;
               default: return false;     
            }
        }
        if(yAxis==0&&xAxis==0) 
            return true;
        else 
            return false;
    }
};

心得体会:
switch语句可以根据字母,数字来进行匹配。每一个case语句都要加break语句。不然会一直执行下去。

题目二

> Given a string, your task is to count how many palindromic substrings in this string.
  The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: “abc”
Output: 3
Explanation: Three palindromic strings: “a”, “b”, “c”.

Example 2:

Input: “aaa”
Output: 6
Explanation: Six palindromic strings: “a”, “a”, “a”, “aa”, “aa”, “aaa”.

分析:
这道题主要就是求一个字符串的回文子串的个数,要注意一个字母也算回文这个特点。在这里我们采取了一个遍历的策略,从字符串的某个字符向两边同时遍历,比较。其中两个SearchSubstrings()函数分别处理aba和abba这两种情况。并且注意在aba以b为圆心遍历时有两个回文串,分别是b和aba。

代码:

class Solution {
public:
    int count=0;
    int countSubstrings(string s) {
        if(s.length()<=0) 
            return false;
        for(int i=0;i<s.length();i++){
            SearchSubstrings(s,i,i);
            SearchSubstrings(s,i,i+1);
        }
        return count;
    }
    void SearchSubstrings(string s,int left,int right){
        while(left>=0&&right<s.length()&&s[left]==s[right]){
            left--; 
            right++;
            count++;
        }
    }
};

心得体会:
有时候while循环要比for循环更合适,把寻找子串单独写成一个函数,程序看起来更加清晰合理。还有在本程序中count为全局变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值