LeetCode字符串(一)

来源:互联网 发布:项目数据分析师含金量 编辑:程序博客网 时间:2024/05/16 18:01

今天主要刷了以下两道题目:**
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为全局变量。