String Problem Strategy

In this post, I would like to talk about several good strategies that you might be able to use for typical string problems. (Only two .. right now.. )

1. Sliding Window
2. Palindrome

Overview

  1. Contiguous Substring - Sliding Window

    • Use left and right pointer to expand/trim the window.

    ABDCSDFACAXC

  2. Palindrome - Middle out algorithm

    • Use mid pointer to investigate whether the string is palindromic or not.

1. Contiguous Substring - Sliding Window

2. Palindromic Substring - Middle out

  • Palindromic Substrings
    • Expand from the middle,
      • Even length of Palindrome : Use two pointers (mid, mid+1)
      • Odd length of Palindrome : Use one pointer (mid)

    palin1

  • Template

    class Solution {
        public boolean Palindrome(String s) {
            int i = s.length()/2;   
              
            if(expandAroundCenter(s, i, i) || expandAroundCenter(s, i, i+1)){
                return true;
            }
            return false;
        }
      
        private boolean expandAroundCenter(String s, int i, int j){
            int Left = i;int Right = j;
      
            while(Left >= 0 && Right < s.length() && s.charAt(Left) == s.charAt(Right)){
                Left --;
                Right ++;
            }
            if(Right == s.length()){
                return true;
            }
            return false;
        }
    }
    
  • Solved - Related Problems

© 2018. All rights reserved.

Powered by Hydejack v8.5.2